Back to Blog

多线程编程(一):线程创建和退出

#多线程#编程#thread#null#join
  • thread: 指向 pthread_t 类型变量的指针,用于存储新创建线程的 ID。
  • attr: 指向 pthread_attr_t 结构体的指针,用于设置线程的属性(如分离状态、调度策略等)。如果为 NULL,则使用默认属性。
  • start_routine: 新线程将要执行的函数。这个函数必须接受一个 void * 类型的参数,并返回一个 void * 类型的值。
  • arg: 传递给 start_routine 函数的参数。如果不需要传递参数,可以设置为 NULL

pthread_create 成功时返回 0,失败时返回错误码。

线程的退出:pthread_exit

线程可以通过多种方式退出:

  1. 线程函数 start_routine 执行完毕并返回。
  2. 线程调用 pthread_exit 函数。
  3. 进程调用 exit 函数,这将终止进程中的所有线程。
  4. 另一个线程调用 pthread_cancel 函数来终止目标线程。

pthread_exit 函数允许线程显式地退出,并返回一个退出状态。