Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

pthread_create 新线程

  • 用于创建新的线程

  • 引用

    #include <pthread.h>
    
    

线程

  • 创建线程

    int pthread_create(
        pthread_t* restrict thread, 
        const pthread_attr_t* restrict attr, 
        void* (*start_routine)(void*), 
        void* restrict arg
    );
    
    • thread —— 指向新创建的线程ID的指针
    • attr —— 指向线程属性的指针,一般为NULL,创建默认属性即可
    • start_routine —— 在新线程中执行的函数的指针
    • arg —— start_routine指向函数的形参指针
    • 创建成功后返回0
    • 使用例子
      #include <stdio.h>
      #include <unistd.h>
      #include <pthread.h>
      void* thread_main(void* arg);
      
      int main() {
          pthread_t t_id;
          int thread_param = 10;
          if (pthread_create(&t_id, NULL, thread_main, (void*)&thread_param) != 0) {
              puts("pthread_create() error");
              return -1;
          }
          sleep(1);
          return 0;
      }
      
      void* thread_main(void* arg) {
          int param = *((int*)arg);
          printf("param: %d", param);
          return NULL;
      }
      
  • 阻塞等待线程

    int pthread_join(pthread_t thread, void** status);
    
    • thread —— 新创建的线程ID,注意不是指针
    • status —— 保存线程返回值的指针变量的地址值
    • 等新线程运行结束后,返回0
    • 使用例子
      #include <stdio.h> //puts
      #include <stdlib.h> //malloc
      #include <unistd.h> //sleep
      #include <string.h> //strcpy
      #include <pthread.h>
      void* thread_main(void* arg);
      
      int main() {
          pthread_t t_id;
          int thread_param = 10;
          if (pthread_create(&t_id, NULL, thread_main, (void*)&thread_param) != 0) {
              puts("pthread_create() error");
              return -1;
          }
      
          void* thread_return;
          if (pthread_join(t_id, &thread_return) != 0) {
              puts("pthread_join() error");
              return -1;
          }
          
          printf("Thread return msg: %s \n", (char*)thread_return);
          sleep(1);
          return 0;
      }
      
      void* thread_main(void* arg) {
          int param = *((int*)arg);
          char* msg = (char*)malloc(sizeof(char) * 10);
          strcpy(msg, "Hello");
          //要用malloc动态分配,不能用栈分配char msg[10] = "Hello";否则无法返回携带信息的指针
          return (void*)msg;
      }
      
  • 销毁线程

    int pthread_detach(pthread_t thread);
    
    • 调用前面的 thread_join 也能在阻塞完返回后销毁
    • 但这里 thread_detach 则不会阻塞主线程
      • 它只是引导线程销毁,否则线程创建的内存空间将一直存在
      • 但由于不阻塞,所以无法获取线程执行完后的返回值