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++
    ~~~~~
  • 相关阅读:
    程序员眼中的 SQL Server-执行计划教会我如何创建索引?
    SQL Server死锁排查
    详解Java中的clone方法 -- 原型模式
    sql-索引的作用(超详细)
    java.util.ConcurrentModificationException 解决办法
    SqlServer索引的原理与应用
    数据库性能优化三:程序操作优化
    数据库性能优化二:数据库表优化
    数据库性能优化一:数据库自身优化(大数据量)
    SQL索引一步到位
  • 原文地址:https://www.cnblogs.com/missmzt/p/4581919.html
Copyright © 2011-2022 走看看