C語言多線程的一個簡單例子


  多線程的一個簡單例子:

  

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>


void * print_a(void *);
void * print_b(void *);

int main(){

    pthread_t t0;
    pthread_t t1;

    // 創建線程A
    if(pthread_create(&t0, NULL, print_a, NULL) == -1){
        puts("fail to create pthread t0");
        exit(1);
    }

    if(pthread_create(&t1, NULL, print_b, NULL) == -1){
        puts("fail to create pthread t1");
        exit(1);
    }

    // 等待線程結束
    void * result;
    if(pthread_join(t0, &result) == -1){
        puts("fail to recollect t0");
        exit(1);
    }

    if(pthread_join(t1, &result) == -1){
        puts("fail to recollect t1");
        exit(1);
    }


    return 0;
}


// 線程A 方法
void * print_a(void *a){
    for(int i = 0;i < 10; i++){
        sleep(1);
        puts("aa");
    }
    return NULL;

}

// 線程B 方法
void * print_b(void *b){
    for(int i=0;i<20;i++){
        sleep(1);
        puts("bb");
    }
    return NULL;
}

 

打印:

aa
bb
aa
aa
bb
...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM