Linux多线程同步入门问题

示例:主线程产生了两个线程,一个模拟生产放入,一个模拟取水果吃

几点注意事项:

  • 引入头文件
  1. #include <pthread.h> 使用多线程时必须引入的头文件
  2. #include <semaphore.h> sem_t结构是信号量的数据类型,它本质上是一个长整型的数。使用sem_*必须引入这个头文件
  • gcc编译
  1. 报错信息:undefined reference to `sem_init';undefined reference to `sem_post';undefined reference to `sem_wait'
  2. 解决方案:gcc编译时需要加入一个多线程选项 gcc -pthread -o filename filename.c

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
int n;
sem_t product,empty;
void *eat(void *arg){
    while (1) {
        printf("**\tSON WANT TO EAT FRUIT\n");
        sem_wait(&product);
        sem_getvalue(&product,&n);
        printf("**\tThere are %d fruits now\n",n);
        sem_post(&empty);
        sleep(10);
    }//while        
}
void *putfruit(void *arg){
    while (1) {//main thread ,put fruit
        printf("Main thread want to put fruit\n");
        sem_wait(&empty);
        sleep(1);
        sem_post(&product);
        sem_getvalue(&product,&n);
        printf("Main: putting fruit in a secs,fruits is %d \n",n);
    }//while       
 }
int main(){
    //Claim process
    pthread_t threadP,threadC;
    //result of process
    void *thread_result1,*thread_result2;
       //flag
    int semi,ret1,ret2;
    semi = sem_init(&empty, 0, 5); //初始设置5个空资源,生产者可连续放入5次
    if (semi == -1) {        printf("sem_init empty failed \n");
        return -1;    }
    semi = sem_init(&product, 0, 0);        //初始设置0个产品数
    if (semi == -1) {        printf("sem_init product failed \n");
        return -1;    }
    ret1 = pthread_create(&threadC, NULL,eat,NULL);
    ret2 = pthread_create(&threadP, NULL,putfruit,NULL);
    if (ret1 != 0|ret2!=0) {        printf("pthread_create failed \n");
        return -1;    }
     ret1 = pthread_join(threadC, &thread_result1);
     ret2 = pthread_join(threadP, &thread_result2);
    if (ret1!=0||ret2!=0)
    {    perror("Thread join failed!\n");
        exit(EXIT_FAILURE);            }//if error
        return 0; } //main

    

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值