全栈开发
C语言
【Q163】如何创建一个线程

如何创建一个线程

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 164 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

创建一个最简单的线程

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
 
void *thread_function(void *arg) {
  printf("hello, world\n");
  sleep(10);
}
 
int main() {
  pthread_t thread;
 
  pthread_create(&thread, NULL, thread_function, NULL);
  pthread_join(thread, NULL);
}

执行它

$ gcc thread.c -std=c99 -lpthread && ./a.out
hello, world