linux 的线程怎么写
时间: 2024-03-02 07:54:04 浏览: 17
在 Linux 下编写线程可以使用 POSIX 线程库(pthread)。下面是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_hello(void *thread_id) {
printf("Hello from thread %ld\n", (long) thread_id);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int rc;
for (long t = 0; t < 5; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void *) t);
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
```
在这个例子中,我们首先包含了 `pthread.h` 头文件。然后,我们定义了一个名为 `print_hello` 的函数,该函数将在线程中运行。这个函数接受一个类型为 `void *` 的参数,可以用来传递任何类型的数据。
在 `main` 函数中,我们首先定义了一个名为 `threads` 的数组,用于存储创建的线程。然后,我们使用 `pthread_create` 函数创建 5 个线程,每个线程都会调用 `print_hello` 函数。`pthread_create` 函数接受 4 个参数:线程标识符、线程属性、线程函数和函数参数。在这个例子中,我们使用了默认的线程属性,将 `print_hello` 函数作为线程函数,并将 `t` 作为函数参数传递。
最后,我们使用 `pthread_exit` 函数退出主线程,等待其他线程继续运行,直到它们完成或被取消。
这只是一个简单的例子,仅用于演示如何在 Linux 下编写线程。实际应用中,你可能需要使用更复杂的线程同步和通信机制,如互斥锁、条件变量、信号量等。