linux 多线程1+2问题

8 篇文章 0 订阅

设计如下功能:

1、设置3个全局变量,初始值为0,分别用于加法的左右值和结果

2、启动线程1,为g_left赋值为1

3、启动线程2,为g_right赋值为2

4、启动线程3,获取g_left+g_right的值

5、线程3需要线程1和线程2执行完后执行

代码:(linux下的多线程编程)

#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "errno.h"
#include "unistd.h"
#include "iostream"
using namespace std;


typedef void*(*fun)(void*);
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;    //申明pthread_mutex_t变量,用作互斥锁变量
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//申明变量,用于pthread_cond_wati和pthread_cond_signal变量
static pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;

int g_left=0;  //定义全局变量
int g_right=0;
int g_add=0;
void* thread_left(void*);  //申明函数
void* thread_right(void*);
void* thread_add(void*);


int main(int argc,char** argv)
{
    printf("--begin:\n");
    pthread_t tid_l,tid_r,tid_a;  //定义线程id类型
    int rc1=0,rc2=0,rc3=0;
    rc1=pthread_create(&tid_l,NULL,thread_left,NULL);  //pthread_create创建线程时成功则返回0,失败返回整数
    if(rc1!=0)
       printf("%s:%d\n",__func__,strerror(rc1)); //strerror打印错误信息
    rc2=pthread_create(&tid_r,NULL,thread_right,&tid_l);
    if(rc2!=0)
       printf("%s:%d\n",__func__,strerror(rc2));
    rc3=pthread_create(&tid_a,NULL,thread_add,&tid_r);
    if(rc3!=0)
       printf("%s:%d\n",__func__,strerror(rc3));
   // sleep(2);
    printf("--end:\n");
    exit(0);
    return 0;
}




void* thread_left(void* arg)
{
    printf("enter the thread_left: \n");
    printf("show the thread_left id is: %d\n",(unsigned int)pthread_self());//pthread_self()获取线程自己的id
    sleep(2);

    pthread_mutex_lock(&mutex); //加锁
    g_left=1;
    printf("the left is: %d\n",g_left);
    pthread_cond_signal(&cond);//发送信号给等待线程
    pthread_mutex_unlock(&mutex); //解锁
    printf("leave the thread_left\n");
    pthread_exit(0);//退出线程
}


void* thread_right(void* arg)
{
    printf("enter the thread_right:\n");
    printf("show the thread_right id is: %d\n",(unsigned int)pthread_self());
    sleep(2);
    pthread_mutex_lock(&mutex);
    pthread_cond_signal(&cond);
    g_right=2;
    printf("the right is: %d\n",g_right);
    pthread_mutex_unlock(&mutex);
    printf("leave the thread_right\n");
    pthread_exit(0);
}


void* thread_add(void* arg)
{
    printf("enter the thread_add:\n");
    printf("show the thread_add id is: %d\n",(unsigned int)pthread_self());
    pthread_mutex_lock(&mutex);
    while(pthread_cond_wait(&cond1,&mutex)&&pthread_cond_wati(&cond,&mutex))
    g_add=g_left+g_right;
    printf("the add is: %d\n",g_add);

    pthread_mutex_unlock(&mutex);
    printf("leave the thread_add\n");
    pthread_exit(0);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值