pthread和std::thread中条件变量的使用

程序很简单,使用两个线程对一个全局变量轮流进行累加。

先来看pthread的版本:

#include 
#include 

pthread_mutex_t lock;
pthread_cond_t cond;

int condition=0;
unsigned long long  g_count=0;

void work1(void * arg)
{
  while (1)
  {
    pthread_mutex_lock(&lock);
    while (condition==1)
    {
      pthread_cond_wait(&cond, &lock);
    }
    condition=1;
    g_count++;
    printf("thread %lld working.current num is %d\n",pthread_self(),g_count);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
  }

}

void work2(void * arg)
{
  while (1)
  {
    pthread_mutex_lock(&lock);
    while (condition==0)
    {
      pthread_cond_wait(&cond, &lock);
    }
    condition=0;
    g_count++;
    printf("thread %lld working.current num is %d\n",pthread_self(),g_count);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
  }

}

int main(int argc, char const *argv[])
{
  pthread_t t1,t2;
  pthread_mutex_init(&lock, NULL);
  pthread_cond_init(&cond, NULL);

  pthread_create(&t1, NULL, work1, NULL);
  pthread_create(&t2, NULL, work2, NULL);
  pthread_join(t1, NULL);
  pthread_join(t2, NULL);

  pthread_mutex_destroy(&lock);
  pthread_cond_destroy(&cond);
  return 0;
}

接下来是std::thread的版本:

#include 
#include 
#include 
#include 
#include 

using namespace std;
using namespace std::chrono;
mutex mtx;
condition_variable cond;
int condition =0;
long long g_count=0;

void work1()
{
  while (1)
  {
    {
      unique_lock lck(mtx);
      while (condition==1)
      {
        cond.wait(lck);
      }
    }

    std::lock_guard lkgrd(mtx);
    g_count++;
    cout<<"thread"< lck(mtx);
      while (condition==0)
      {
        cond.wait(lck);
      }
    }

    std::lock_guard lkgrd(mtx);
    g_count++;
    cout<<"thread"<

实际运行的时候,pthread的版本要快一些。

PS:C++11 中线程库风格与pthread类似。和win32 thread 有区别。win32 thread中没有条件变量这个概念,与之对应的是事件(EVENT)。

你可能感兴趣的:(C/C++基础知识,unix程序设计/网络编程,pthreadm,C++11,条件变量)