分类: LINUX
2010-07-09 14:44:13
与进程类似,线程的操作也存在互斥和共享的问题。
同步机制有互斥锁和信号量。
本实验用到互斥锁功能,系统调用有:pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, pthread_mutex_destroy.
源代码来自华清远见:
#include
#include
#include
#define THREAD_NUMBER 3
#define REPEAT_NUMBER 3
#define DELAY_TIME_LEVELS 10.0
pthread_mutex_t mutex;
void *thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time = 0;
int count = 0;
int res;
res = pthread_mutex_lock(&mutex);//上锁
if(res)
{
printf("Thread % lock failed\n", thrd_num);
pthread_exit(NULL);
}
printf("Thread %d is starting\n", thrd_num);
for(count = 0; count < REPEAT_NUMBER; count++)
{
delay_time = (int) (rand() *DELAY_TIME_LEVELS/(RAND_MAX) + 1);
sleep(delay_time);
printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time);
}
printf("Thread %d finished\n", thrd_num);
pthread_exit(NULL);
}
int main()
{
pthread_t thread[THREAD_NUMBER];
int no = 0, res;
void *thrd_ret;
srand(time(NULL));
pthread_mutex_init(&mutex, NULL);//互斥锁初始化
for(no = 0; no < THREAD_NUMBER; no++)
{
res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);//创建线程
if(res != 0)
{
printf("Create thread %d failed\n", no);
exit(res);
}
}
printf("Create threads success\nWaiting for threads to finish..\n");
for(no = 0; no < THREAD_NUMBER; no++)
{
res = pthread_join(thread[no], &thrd_ret);//挂起线程
if(!res)
{
printf("Thread %d joined\n", no);
}
else
{
printf("Thread %d join failed\n", no);
}
pthread_mutex_unlock(&mutex);//解锁
}
pthread_mutex_destroy(&mutex);
return 0;
}
编译运行,结果如下:
观察运行结果与上次试验比较,发现3个线程的运行顺序与创建顺序相同。而上次没有加锁的线程运行是独立无序的。由此可见互斥锁实现了同步的功能。