习惯于在java下使用synchronized关键词来进行线程同步控制,在C++下接到需要进行线程同步的任务时突然有点蒙,然后第一反应是回忆起了《操作系统》课上老师说过的原子操作,于是百度一番找到了atomic.h这个提供原子操作的头文件,可惜的是给定的环境中并没有提供这个头文件,经过一番请教结果发现pthread.h中本就提供了线程同步控制的方法:互斥锁mutex
为了验证同步的实现情况,我们假设这样一个情景,我们需要向一个容器中交替写入“12345”和“678910”两种序列,通过mutex进行线程同步控制
示例代码如下:
1.实现序列 6 1 7 2 8 3 9 4 10 5 6 1 ......
#include <iostream>
#include <vector>
#include <pthread.h>
using namespace std;
vector<int> v;
pthread_mutex_t mutex;
void* fun1( void* )
{
while(true)
{
// sleep(1);
// pthread_mutex_lock( &mutex );
for( int i=1 ; i<=5 ; i++ )
{
v.push_back(i);
sleep(1);
}
// pthread_mutex_unlock( &mutex );
// sleep(1);
}
return NULL;
}
void* fun2( void* )
{
while(true)
{
// sleep(1);
// pthread_mutex_lock( &mutex );
for( int i=6 ; i<=10 ; i++ )
{
v.push_back(i);
sleep(1);
}
// pthread_mutex_unlock( &mutex );
// sleep(1);
}
return NULL;
}
int main()
{
pthread_mutex_init( &mutex , NULL );
pthread_t PID1;
pthread_t PID2;
pthread_create( &PID1 , NULL , fun1 , NULL );
pthread_create( &PID2 , NULL , fun2 , NULL );
while( true )
{
for( vector<int>::const_iterator it=v.begin() ; it!=v.end() ; it++ )
cout << *it << ' ';
cout << endl;
sleep(1);
}
}
试过将里面的sleep()注释掉,结果会产生一个线程循环进行,而另一个进程无法进入push_back函数的情况,可以推测push_back内部也是做了一些同步控制,而且很可能这个函数是阻塞等待的。但这种无限等待按理说不应该出现,毕竟线程调度设计时应该是避开饥饿问题的,这个问题值得继续调研一下。
2.实现序列 6 7 8 9 10 1 2 34 5 6 7 ......
#include <iostream>
#include <vector>
#include <pthread.h>
using namespace std;
vector<int> v;
pthread_mutex_t mutex;
void* fun1( void* )
{
while(true)
{
// sleep(1);
// pthread_mutex_lock( &mutex );
for( int i=1 ; i<=5 ; i++ )
{
v.push_back(i);
sleep(1);
}
pthread_mutex_unlock( &mutex );
sleep(1);
}
return NULL;
}
void* fun2( void* )
{
while(true)
{
// sleep(1);
pthread_mutex_lock( &mutex );
for( int i=6 ; i<=10 ; i++ )
{
v.push_back(i);
sleep(1);
}
// pthread_mutex_unlock( &mutex );
sleep(1);
}
return NULL;
}
int main()
{
pthread_mutex_init( &mutex , NULL );
pthread_t PID1;
pthread_t PID2;
pthread_create( &PID1 , NULL , fun1 , NULL );
pthread_create( &PID2 , NULL , fun2 , NULL );
while( true )
{
for( vector<int>::const_iterator it=v.begin() ; it!=v.end() ; it++ )
cout << *it << ' ';
cout << endl;
sleep(1);
}
}
3.实现其他序列
不一一列举了,通过对上面代码中几个sleep()函数的是否注释,这一段代码还能构造一些比较有意思的序列,而且通过分析这些序列也可以从中猜测和验证一些vector和系统调度的实现方法。