今天刚学的,linux多线程编程

今天学的是多线程编程,下面是一个典型的例子。

学的东西时间久了总会忘,写下来是最好的办法,以后一看就记起来了!

程序的实现是写入数据到buf中,然后在终端显示,直到输入exit退出为止。

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#define BUFSIZE 128

pthread_mutex_t mutex;
pthread_cond_t cond;
char buf[BUFSIZE];
int buf_has_data = 0;


void *read(void *arg)
{
	do{
		pthread_mutex_lock(&mutex);//对数据操作时,锁上,避免别的线程同时操作
		
		if (buf_has_data == 0)/*BUF中没有数据时把READ线程挂起,释放占用CPU的资源,等待别的线程把它唤醒*/
		{
			pthread_cond_wait(&cond,&mutex);
		}

		printf("[%s] in the buffer\n",buf);
		buf_has_data = 0;

		pthread_cond_signal(&cond);//唤醒write线程,并把write线程中的数据锁锁上	
		pthread_mutex_unlock(&mutex);

	}while(strcmp(buf,"exit") != 0);	
}

void *write(void *arg)
{
	do{
		pthread_mutex_lock(&mutex);

		if (buf_has_data == 1)//buf中的数据没被读走就write线程挂起等待唤醒
		{
			pthread_cond_wait(&cond,&mutex);
		}

		printf("input:");
		gets(buf);
		buf_has_data = 1;

		pthread_cond_signal(&cond);//唤醒read线程,并把read线程中的数据锁锁上	
		pthread_mutex_unlock(&mutex);

	}while(strcmp(buf,"exit") != 0);	
	
}


int main()
{
	pthread_t read_thread;
	pthread_t write_thread;

	
	pthread_mutex_init(&mutex,NULL);//initialize mutex
	pthread_cond_init(&cond,NULL);//initialize cond
	
	/*creat the thread*/
	pthread_create(&read_thread,NULL,read,NULL);
	pthread_create(&write_thread,NULL,write,NULL);

	/*wait the child thread end*/
	pthread_join(read_thread,NULL);
	pthread_join(write_thread,NULL);


	/*destroy mutex and cond*/
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	return 0;
}


你可能感兴趣的:(JOIN,thread,多线程,linux,null,Signal)