相关函数
pthread_mutex_init()
pthread_mutex_lock()
pthread_mutex_trylock()
pthreaad_mutex_unlock()
pthread_mutex_destroy()
请看下面一个程序:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
char buf[40] = {0};
void read_buf() //读缓冲区
{
int i;
for(i=0; i<10; i++)
{
sleep(5);
if(0 == strlen(buf))
{
printf("No message.\n");
}
else
{
printf("Read buf:%s\n", buf);
bzero(buf, sizeof(buf));
}
sleep(1); //这里sleep(1)是为了让CPU有机会去调用另外的线程
}
}
void write_buf() //写缓冲区
{
int i;
for(i=0; i<10; i++)
{
bzero(buf, sizeof(buf));
sprintf(buf, "This is message %d.", i+1);
sleep(1); //这里sleep(1)是为了让CPU有机会去调用另外的线程
}
}
int main()
{
pthread_t tid1, tid2;
int ret;
ret = pthread_create(&tid1, NULL, (void *)read_buf, NULL);
if(ret != 0)
{
perror("pthread_create.");
exit(1) ;
}
ret = pthread_create(&tid2, NULL, (void *)write_buf, NULL);
if(ret != 0)
{
perror("pthread_create.");
exit(1) ;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
我们来看一下运行结果:
Read buf:This is message 5.
Read buf:This is message 10.
No message.
No message.
No message.
No message.
No message.
No message.
No message.
No message.
很明显,线程1在读之前睡了5s,导致线程2已经将buf重写了5次了。
但如果我想让线程1在读之前buf里的数据是没有改动过的,也就是说线程1要读到每次改动的数据。这跟系统在读写文件时是一样的,如果一个线程在读一个文件时该文件被另一个线程执行写操作,那么可能会造成不可预知的错误。而要保证读的操作不会受影响,则对文件的读写操作必须是同步的,也就是说要在同一时间只能执行写操作和读操作中的一个。那么,我们就需要用互斥锁来解决问题。(在本例中把sleep(5)也当成是读操作的一部分。)
修改后的程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
char buf[40] = {0};
pthread_mutex_t mutex;
void read_buf()
{
int i;
for(i=0; i<10; i++)
{
pthread_mutex_lock(&mutex); //上锁
sleep(5);
if(0 == strlen(buf))
{
printf("No message.\n");
}
else
{
printf("Read buf:%s\n", buf);
bzero(buf, sizeof(buf));
}
pthread_mutex_unlock(&mutex); //解锁
sleep(1); //这里sleep(1)是为了让CPU有机会去调用另外的线程
}
}
void write_buf()
{
int i;
for(i=0; i<10; i++)
{
pthread_mutex_lock(&mutex); //上锁。这里如果read_buf没有释放锁,那么这里将一直阻塞,也就不会在read_buf中sleep(5)的时候修改buf的值了。
bzero(buf, sizeof(buf));
sprintf(buf, "This is message %d.", i+1);
pthread_mutex_unlock(&mutex); //解锁
sleep(1); //这里sleep(1)是为了让CPU有机会去调用另外的线程
}
}
int main()
{
pthread_t tid1, tid2;
int ret;
pthread_mutex_init(&mutex, NULL);
ret = pthread_create(&tid1, NULL, (void *)read_buf, NULL);
if(ret != 0)
{
perror("pthread_create.");
exit(1) ;
}
ret = pthread_create(&tid2, NULL, (void *)write_buf, NULL);
if(ret != 0)
{
perror("pthread_create.");
exit(1) ;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
我们来看一下运行结果:
No message.
Read buf:This is message 1.
Read buf:This is message 2.
Read buf:This is message 3.
Read buf:This is message 4.
Read buf:This is message 5.
Read buf:This is message 6.
Read buf:This is message 7.
Read buf:This is message 8.
Read buf:This is message 9.
这样就可以顺利读到每次修改的数据了。
pthread_trylock()是pthread_lock()的非阻塞函数,也就是调用pthread_trylock()发现产生死锁时会通过errno返回EBUSY。而pthread_lock()函数在遇到死锁时会一直阻塞。