【Linux】 Pthread的基本使用

1.創建一個簡單的線程

函數原型:int pthread_create( pthread_t *thread,  const pthread_attr_t *attr,  void *(*start_routine) (void *),  void *arg);

                 功能:創建一個線程(成功返回<0, 失敗返回 > 0.)
                 參數:線程ID,線程屬性 (一般不用爲NULL),線程執行函數  ,線程執行函數參數

函數原型:int pthread_join(pthread_t thread, void **thread_return);

                功能:等待線程的結束   (成功返回0,失敗返回其他)
                參數:   線程ID(要結束的線程),線程退出的時候的返回參數指針

函數原型:int pthread_exit(void *retval);
                功能:在創建的線程中調用,代表結束當前線程。
                參數:   局部變量 返回指針

#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
#include "string.h"
#include "pthread.h"

char message[] = "hello world";

void *Thread_A(void* arg)
{
   printf("thread is running!!!!\n");
   sleep(3);
   strcpy(message, "Bye");// message[] == "Bye"
   pthread_exit("Thank you using CPU!!!!!!\n");//退出當前線程,並且返回字符串
}


int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;
    
    res = pthread_create(&a_thread, NULL, Thread_A, message);//創建線程
    if(res != 0){  printf("error create thread");  }
    printf("thread waiting for finish \n");
    
    res = pthread_join(a_thread, &thread_result);//thread_result爲pthread_exit()的返回值
    if(res != 0){  printf("error thread join "); }
    printf("thread joined, it returned %s ", (char*)thread_result);

    printf("message is %s \n", message); 
}

 

 

2.證明主線程和創建的子線程同時執行(即能夠交替打印1,2)

#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
#include "string.h"
#include "pthread.h"

char message[] = "hello world";
int run_now = 1;

void *Thread_A(void* arg)
{
    int print_count2 = 0;
    while(print_count2++ < 20) {
        if (run_now == 2) {
            printf("2");//-----------3,7
            run_now = 1; 
        }
        else {  sleep(1);  }//在Sleep的時候,切換到a_thread進程------4,8
    }
}


int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;
    
    res = pthread_create(&a_thread, NULL, Thread_A, message);// message[] == "hello world"
    if(res != 0){  printf("error create thread");  }

{
    int print_count1 = 0;
    while(print_count1++ < 20) {//程序進入此循環
        if (run_now == 1) {
            printf("1");//------------------1,5
            run_now = 2; 
        }
        else {  sleep(1);  }//在Sleep的時候,切換到a_thread進程----------2,6
    }
}

    printf("\n thread waiting for finish \n");
    
    res = pthread_join(a_thread, &thread_result);//thread_result == Thread_A return  "Thank you using CPU!!!!!!"
    if(res != 0){  printf("error thread join "); }
    printf("thread joined, it returned %s ", (char*)thread_result);

    printf("message is %s \n", message);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章