linux编写一个C程序,使用 pthread_create() 函数创建一个或多个线程。 - 定义线程函数,该函数将被新创建的线程执行。 - 在主线程中等待所有子线程结束,可以使用 pthread_join() 函数。
时间: 2024-09-27 07:14:34 浏览: 112
在 Linux 环境下,编写 C 程序利用 `pthread_create()` 函数创建线程通常涉及以下几个步骤:
1. **包含头文件**:
首先,你需要在程序中包含 `pthread.h` 头文件,它包含了与线程处理相关的函数声明。
```c
#include <pthread.h>
```
2. **定义线程函数 (Thread Function)**:
这是你想要在线程中运行的具体功能,一般需要一个原型。例如,你可以定义一个名为 `thread_function` 的函数,接收一个参数并打印一条消息。
```c
void *thread_function(void *arg) {
char *msg = (char *) arg;
printf("Thread %d: %s\n", pthread_self(), msg);
// 在这里添加你的实际操作
return NULL;
}
```
这里的 `pthread_self()` 返回当前线程的标识符。
3. **创建线程**:
使用 `pthread_create()` 创建新线程,并指定线程函数、参数以及一个用于存储返回值的指针(对于 `void*` 类型的线程函数,通常不需要这个返回值)。
```c
int thread_id;
pthread_t tid;
// 参数是一个指向线程函数的指针,以及传递给线程函数的数据
thread_id = pthread_create(&tid, NULL, thread_function, "Hello from child thread");
if (thread_id != 0) {
perror("Error creating thread");
exit(1);
}
```
4. **等待线程结束**:
如果你想让主线程等待子线程完成,可以使用 `pthread_join()` 函数。这会阻塞主线程直到子线程结束。
```c
if (pthread_join(tid, NULL) != 0) {
perror("Error joining thread");
exit(1);
}
printf("Main thread: All threads finished.\n");
```
5. **清理资源**:
最后别忘了释放线程相关的资源,如取消标志 (`pthread_cancel`) 或销毁线程 (`pthread_exit`),以及清理分配给线程的数据。
完整的示例代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg) {
char *msg = (char *) arg;
printf("Thread %d: %s\n", pthread_self(), msg);
return NULL;
}
int main() {
int thread_id;
pthread_t tid;
thread_id = pthread_create(&tid, NULL, thread_function, "Child Thread 1");
if (thread_id != 0) {
perror("Error creating thread");
exit(1);
}
// 创建第二个线程...
thread_id = pthread_create(&tid, NULL, thread_function, "Child Thread 2");
if (thread_id != 0) {
perror("Error creating second thread");
exit(1);
}
if (pthread_join(tid, NULL) != 0) {
perror("Error joining first thread");
exit(1);
}
if (pthread_join(tid, NULL) != 0) {
perror("Error joining second thread");
exit(1);
}
printf("Main thread: All threads finished.\n");
return 0;
}
```
阅读全文
相关推荐
















