为使系统中的多线程能有条不紊地运行,在系统中必须提供用于实现线程间同步和通信的机制。为了支持不同频率的交互操作和不同程度的并行性,在多线程OS中通常提供多种同步机制,如互斥锁、条件变量、计数信号量以及多读、单写锁等,下面就以互斥锁为例实现线程同步。
其中, 程序中有两个线程,A、B , 线程A是主线程,主要负责读取用户从终端中输入的字符串;而线程B是新建的线程,主要用于判断读取的字符串是否为结束符,如果不是,则向终端打印出刚才输入的字符串的长度并等待再次输入,否则结束程序。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
int time_to_exit=0; /*互斥量,保护工作区及额外变量time_to_exit*/
#define WORK_SIZE 1024
char work_area[WORK_SIZE]; /*工作区*/
int main()
{
int res ;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex,NULL); /*初始化工作区*/
if(res!=0){
perror("Mutex initialization failed");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread,NULL,thread_function,NULL); /*创建新线程*/
if(res!=0){
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
/*主线程A*/
pthread_mutex_lock(&work_mutex); //主线程对互斥量加锁
printf("Input some text. Enter 'end' to finish\n");
while(!time_to_exit){//当线程B遇到结束符后会将变量置为非零以结束循环
fgets(work_area,WORK_SIZE,stdin); //从终端向工作区中输入字符串
pthread_mutex_unlock(&work_mutex); //解锁互斥量
while(1){
pthread_mutex_lock(&work_mutex); // 这里必须等待线程B释放后才能加锁,否则只能一直等待
if(work_area[0]!='\0'){
pthread_mutex_unlock(&work_mutex);
sleep(1);
}else{
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\nWaiting for thread to finish...\n");
res = pthread_join(a_thread,&thread_result); //父线程等待子线程终止
if(res!=0){
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined\n");
pthread_mutex_destroy(&work_mutex);
exit(EXIT_SUCCESS);
}
/*新线程B*/
void *thread_function(void *arg)
{
sleep(1);
pthread_mutex_lock(&work_mutex);//等待线程A读取字符串并解锁后将互斥量加锁,以获取工作区资源
while(strncmp("end",work_area,3)!=0){//判断是否遇到结束符end
printf("You input %d characters\n",strlen(work_area)-1);
work_area[0]='\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while(work_area[0]=='\0'){//通过将第一个字符设置为NULL,通知线程A已完成字符统计
pthread_mutex_unlock(&work_mutex);//解锁互斥量并等待线程A继续运行
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\0' ;
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
在该程序中,新线程首先试图对互斥量加锁。如果它已经被加锁,这个调用将被阻塞直到锁被释放为止。一旦获得访问权,新线程将检查是否有申请退出程序的请求。如果有,就简单设置time_to_exit变量,再把工作区的第一个字符设置为'\0',然后退出。如果不想退出,就对字符个数进行统计。然后把work_area数组中的第一个字符设置为'\0'。通过将第一个字符设置为NULL,通知线程A已完成字符统计。随后解锁互斥量并等待主线程继续运行。程序将周期性地尝试给互斥量加锁,如加锁成功,则检查主线程是否又有字符串需要统计。如没有,则解锁互斥量继续等待;否则将统计字符个数,并再次进入循环。