zoukankan      html  css  js  c++  java
  • linux:C++多线程编程小结

    mark: 在多线程中使用 cout打印输出时会出现乱序, printf则没有该现象.

    参考:http://www.cnblogs.com/gnuhpc/archive/2012/12/07/2807484.html

      http://www.cnblogs.com/xianghang123/archive/2011/08/11/2134927.html

    ·线程创建

      函数原型:int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);

      返回值:若是成功建立线程返回0,否则返回错误的编号。  

       形式参数:pthread_t *restrict tidp 要创建的线程的线程id指针,即,创建成功后,该指针指向的内存存放创建线程的id;const pthread_attr_t *restrict attr创建线程时的线程属性;void* (start_rtn)(void)返回值是void类型的指针函数;void *restrict arg start_rtn的形参。

      ·线程挂起:该函数的作用使得当前线程挂起,等待另一个线程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。

      函数原型:int pthread_join( pthread_t thread, void **value_ptr);

      参数说明如下:thread等待退出线程的线程号;value_ptr退出线程的返回值。

      ·线程退出

      函数原型:void pthread_exit(void *rval_ptr);

      ·获取当前线程id

      函数原型:pthread_t pthread_self(void);

      ·互斥锁

      创建pthread_mutex_init;销毁pthread_mutex_destroy;加锁pthread_mutex_lock;解锁pthread_mutex_unlock。

      ·条件锁

      创建pthread_cond_init;销毁pthread_cond_destroy;触发pthread_cond_signal;广播pthread_cond_broadcast S;等待pthread_cond_wait

    实例代码;

     1 #include <pthread.h>
     2 #include <iostream>
     3 using namespace std;
     4 void *TestThread(void* arg)
     5 {
     6   int input = *(int*)arg;
     7   cout << "threadId: "<< input <<"running"<<endl;
     8 }
     9 
    10 int main()
    11 {
    12   pthread_t threadId;
    13   int input = 12;
    14   int ret = pthread_create(&threadId, NULL, TestThread, (void*)&input);
    15   if(ret != 0)
    16    {
    17     cout<< "create thread error"<<endl;
    18    }
    19 
    20   cout<<"main thread running"<<endl;
    21   pthread_join(threadId,NULL);
    22 
    23   return 0;
    24 }


    互斥锁与条件变量以及信号量介绍:
    互斥锁:互斥锁用来对共享资源的互斥访问,一个时刻只允许一个线程资源的修改.
    pthread_mutex_t mutex;   pthread_mutex_lock(&mutex);
    pthread_mutex_unlock(&mutex);
    条件变量: 条件变量的作用是当一个线程的继续运行依赖于一个条件,而这个条件是由另一个线程触发的,这时候使用互斥锁是不行的.
    pthread_cond_t cond; pthread_cond_wait(&cond,&mutex); pthread_cond_signal(&cond);
    pthread_cond_wait,两个参数第一个是等待的条件量,第二个是要释放的互斥锁,pthread_cond_wait时,阻塞当前线程,等待条件变化,同时释放自己占有的互斥锁,使得其他线程可以运行从而触发条件量,在另一个线程中使用pthread_cond_signal 来告诉被阻塞的线程继续运行.

    信号量:当共享资源有限时,如消费缓冲区,多个线程同时去进行消费,当缓冲区资源为0时,不允许新的线程进入,则使用信号量机制进行限制.信号量一般和互斥锁接合使用,前者用来限制线程进入缓冲区的数目,后者用于互斥的修改缓冲区资源.
    sem_t sem_id; sem_wait(&sem_id);取得信号量,sem_id的值--,若为0,则等待 sem_post(&sem_id);释放信号量,sem_id++
    ~~~~~
  • 相关阅读:
    LintCode Python 简单级题目 488.快乐数
    LintCode Python 简单级题目 100.删除排序数组中的重复数字 101.删除排序数组中的重复数字II
    LintCode Python 简单级题目 373.奇偶分割数组
    LintCode Python 简单级题目 39.恢复旋转排序数组
    LintCode Python 简单级题目 35.翻转链表
    LintCode Python 简单级题目 451.两两交换链表中的节点
    LintCode Python 简单级题目 174.删除链表中倒数第n个节点
    aws查看官方centos镜像imageid
    linux shell脚本查找重复行/查找非重复行/去除重复行/重复行统计
    php配置优化-生产环境应用版
  • 原文地址:https://www.cnblogs.com/missmzt/p/4581919.html
Copyright © 2011-2022 走看看