程序很简单,使用两个线程对一个全局变量轮流进行累加。
先来看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)。