您的位置:首页 > 运维架构 > Linux

linux:C++多线程编程小结

2015-06-22 11:21 681 查看
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

实例代码;

#include <pthread.h>
#include <iostream>
using namespace std;
void *TestThread(void* arg)
{
  int input = *(int*)arg;
  cout << "threadId: "<< input <<"running"<<endl;
}

int main()
{
  pthread_t threadId;
  int input = 12;
  int ret = pthread_create(&threadId, NULL, TestThread, (void*)&input);
  if(ret != 0)
   {
    cout<< "create thread error"<<endl;
   }

  cout<<"main thread running"<<endl;
  pthread_join(threadId,NULL);

  return 0;
}


互斥锁与条件变量以及信号量介绍:
互斥锁:互斥锁用来对共享资源的互斥访问,一个时刻只允许一个线程资源的修改.
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++
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: