线程间通信是利用全局变量来进行通讯的。在多文件编程下,全局变量的引用声明该如何做呢?
下面写一个从标准输入读数据,并且在标准输出打印数据的小程序,来演示一下。
-----thread.h---------------------------------------------
#ifndef thread_h
#define thread_h
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define N 32
sem_t sem;
char buf[N] = {}; //带外部链接的静态存储类,如果在头文件中使用带内部链接的静态存储类的话,则系统会在预处理阶段将
//这个引用声明复制到每一个源文件中。
#endif
------ffgets.c-------------------------------------
#include "thread.h"
void *ffgets(void *arg)
{
extern char buf[N];
while(1)
{
fgets(buf, sizeof(buf), stdin);
sem_post(&sem);
if(strncmp(buf, "quit", 4) == 0)
break;
}
pthread_exit("ffgets exit");
}
------ffputs.c-------------------------------------
#include "thread.h"
void *ffputs(void *arg)
{
extern char buf[N];
while(1)
{
sem_wait(&sem);
if(strncmp(buf, "quit", 4) == 0)
break;
fputs(buf, stdout);
}
pthread_exit("ffgets exit");
}
------main.c-------------------------------------
#include "thread.h"
int main(int argc, const char *argv[])
{
pthread_t tid1, tid2;
void *ret1, *ret2;
sem_init(&sem, 0, 0);
if(pthread_create(&tid1, NULL, ffgets, NULL) != 0)
{
perror("create");
return -1;
}
if(pthread_create(&tid2, NULL, ffputs, NULL) != 0)
{
perror("create");
return -1;
}
pthread_join(tid1, &ret1);
pthread_join(tid2, &ret2);
sem_destroy(&sem);
return 0;
}
----Makefile----------------------------------------
obj:=$(patsubst %.c, %.o, $(wildcard *.c))
.PHONY:
clean
main:$(obj)
cc -o main $(obj) -pthread
clean:
-rm *.o main