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

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

先来看pthread的版本:

#include <pthread.h>
#include <stdio.h>

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 <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

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<mutex> lck(mtx);
      while (condition==1)
      {
        cond.wait(lck);
      }
    }

    std::lock_guard<mutex> lkgrd(mtx);
    g_count++;
    cout<<"thread"<<this_thread::get_id()<<"is working. "<<" current num is "<< g_count<<endl;
    condition=1;
    cond.notify_all();
  }

}

void work2()
{
  while (1)
  {
    {
      unique_lock<mutex> lck(mtx);
      while (condition==0)
      {
        cond.wait(lck);
      }
    }

    std::lock_guard<mutex> lkgrd(mtx);
    g_count++;
    cout<<"thread"<<this_thread::get_id()<<"is working. "<<" current num is "<< g_count<<endl;
    condition=0;
    cond.notify_all();
  }

}

int main()
{
  thread t1(work1);
  thread t2(work2);

  t1.join();
  t2.join();
}

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值