线程间通信之信号量(多文件编程,全局变量的问题)

线程间通信是利用全局变量来进行通讯的。在多文件编程下,全局变量的引用声明该如何做呢?
下面写一个从标准输入读数据,并且在标准输出打印数据的小程序,来演示一下。

-----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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值