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

【Linux】 Pthread的基本使用_第1张图片

 

 

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

}

你可能感兴趣的:(Linux)