1. 程式人生 > >Linux-(C)多執行緒學習(入門)

Linux-(C)多執行緒學習(入門)

下面兩個仁兄總結非常好。

主要學習一個例子:

/*
 * test1.c
 *
 *  Created on: 2016年7月26日
 *      Author: Andy_Cong
 */

/*
 * 利用多執行緒與有名管道技術,
 * 實現兩個程序之間傳送即時訊息,實現聊天功能。
 * */
//mkfifo xx  (新建一個管道xx)
//兩個程式test1 test2 兩個管道fofi1 fofi2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include<errno.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void *writefofi(void *arg)
{
	char *filename=(char *)arg;
	int fd=open(filename,O_WRONLY);
	if(fd==-1)
	{
		printf("open error is: %s\n",strerror(errno));
		return NULL;
	}
	char buf[1024];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		read(STDOUT_FILENO,buf,sizeof(buf));
		write(fd,buf,strlen(buf));
	}
	close(fd);
	return NULL;
}
void *readfofi(void *arg)
{
	char *filename = (char *) arg;
	int fd = open(filename, O_RDONLY);
	if (fd == -1)
	{
		printf("open error is: %s\n", strerror(errno));
		return NULL;
	}
	char buf[1024];
	while (1)
	{
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("%s",buf);
	}
	close(fd);
	return NULL;
}


int main(int argc,char *argv[])
{
	if(argc<3)
		return 0;
	pthread_t thrd1,thrd2;
	char *writefile=argv[1];
	char *readfile=argv[2];
	pthread_create(&thrd1,NULL,writefofi,(void *)writefile);
	pthread_create(&thrd2,NULL,readfofi,(void *)readfile);
	pthread_join(thrd1,NULL);
	pthread_join(thrd2,NULL);
	return 0;
}
/*
 * test2.c
 *
 *  Created on: 2016年7月26日
 *      Author: Andy_Cong
 */


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include<errno.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void *writefofi(void *arg)
{
	char *filename=(char *)arg;
	int fd=open(filename,O_WRONLY);
	if(fd==-1)
	{
		printf("open error is: %s\n",strerror(errno));
		return NULL;
	}
	char buf[1024];
	while(1)
	{
		memset(buf,0,sizeof(buf));
		read(STDOUT_FILENO,buf,sizeof(buf));
		write(fd,buf,strlen(buf));
	}
	close(fd);
	return NULL;
}
void *readfofi(void *arg)
{
	char *filename = (char *) arg;
	int fd = open(filename, O_RDONLY);
	if (fd == -1)
	{
		printf("open error is: %s\n", strerror(errno));
		return NULL;
	}
	char buf[1024];
	while (1)
	{
		memset(buf, 0, sizeof(buf));
		read(fd, buf, sizeof(buf));
		printf("%s",buf);
	}
	close(fd);
	return NULL;
}


int main(int argc,char *argv[])
{
	if(argc<3)
		return 0;
	pthread_t thrd1,thrd2;
	char *writefile=argv[1];
	char *readfile=argv[2];
	pthread_create(&thrd1,NULL,writefofi,(void *)writefile);
	pthread_create(&thrd2,NULL,readfofi,(void *)readfile);
	pthread_join(thrd1,NULL);
	pthread_join(thrd2,NULL);
	return 0;
}





執行結果: