今日習ったばかりの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
",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; }