a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > C > 正文

linux c多線程編程實例代碼

2020-01-26 15:42:06
字體:
來源:轉載
供稿:網友

直接看代碼吧,代碼里有注釋

復制代碼 代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#define MAX 3

int number =0;
pthread_t id[2];
pthread_mutex_t mut; //初始化靜態互斥鎖

void thread1(void)
{
    int i;
    printf("Hello,I am pthread1!/n");
    for (i=0; i<MAX; i++)
    {
        pthread_mutex_lock(&mut);  //此處上鎖,保證number的唯一性
            number ++;  
            printf("Thread1:number = %d/n",number);
        pthread_mutex_unlock(&mut);
        sleep(1);  //linux c下 sleep(minute),里面變量單位是分鐘
    }
    pthread_exit(NULL); //線程通過執行此函數,終止執行。返回是一個空指針類型
}

void thread2(void)
{
    int j;
    printf("Hello,I'm pthread2/n");
    for(j=0; j<MAX; j++)
    {
        pthread_mutex_lock(&mut);
             number ++;
             printf("Thread2:number = %d/n",number);
        pthread_mutex_unlock(&mut);
        sleep(1);
    }
    pthread_exit(NULL);
}

void thread_create(void)
{
    int temp;
    memset(&id, 0, sizeof(id));
if(temp = pthread_create(&id[0], NULL, (void *)thread1, NULL)!= 0)
                          //參數:線程標識符指針 線程屬性  線程運行函數起始地址  運行函數屬性
                          //創建成功返回 0
        printf("Thread 1 fail to create!/n");
    else
        printf("Thread 1 created/n");
    if(temp = pthread_create(&id[1], NULL, (void *)thread2, NULL)!= 0)
        printf("Thread 2 fail to create!/n");
    else
        printf("Thread 2 created!/n");
 }  
void thread_wait()
{
    if(id[0] != 0)
    {
        pthread_join(id[0], NULL); //等待線程結束,使用此函數對創建的線程資源回收
        printf("Thread1 completed!/n");
    }
    if(id[1] != 0)
    {
        pthread_join(id[1], NULL);
        printf("Thread2 completed!/n");
    }
}
int main(void)
{
int i,ret1,ret2;
pthread_mutex_init(&mut, NULL); //動態互斥鎖
    printf("Main fuction,creating thread.../n");
    thread_create();
    printf("Main fuction, waiting for the pthread end!/n");
    thread_wait();
    return (0);
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 国产精品8888 | 在线观看xxx| 精品国模一区二区三区欧美 | 日韩成人免费 | 美女一区二区三区四区 | 国产成人精品一区二区三区网站观看 | 成人久久18免费网站图片 | 99精品欧美一区二区三区 | 亚洲欧美中文日韩v在线观看 | 午夜日韩在线 | 国产精品一区二区三区免费视频 | 一级毛片免费看 | 午夜视 | 国产精品对白一区二区三区 | 午夜视频你懂得 | 九九热在线免费视频 | 久久91精品国产 | 欧美性一区二区 | 亚洲日韩欧美一区二区在线 | 久久久成人网 | eeuss影院一区二区三区 | 国产精品伦理 | www.国产视频 | 不卡成人| 九九99九九精彩46 | 日韩免费精品视频 | 成人免费黄色片 | 操久久| 99热首页| 日韩成人综合 | 中文字幕av一区二区三区 | 天天宗合网 | 在线成人www免费观看视频 | 亚洲品质自拍视频网站 | 国产拍揄自揄精品视频麻豆 | 午夜视频一区二区 | 亚洲欧美日韩另类精品一区二区三区 | 欧美成人精品一区 | 日本美女黄网站 | 国产一级做a爰片在线看免费 | 色站综合 |