1. 程式人生 > >linux 多執行緒1+2問題

linux 多執行緒1+2問題

設計如下功能:

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);
}