在多线程编程中,`pthread_create()` 是一个非常重要的函数,用于创建一个新的线程。简单来说,它就像给程序添加了一个“分身”,让任务可以并行执行。
首先,你需要包含头文件 `
```c
int pthread_create(pthread_t thread, const pthread_attr_t attr,
void (start_routine) (void ), void arg);
```
- `thread`:存储新线程的 ID。
- `attr`:设置线程属性(通常设为 NULL)。
- `start_routine`:线程执行的函数入口地址。
- `arg`:传递给线程函数的参数。
例如:
```c
include
include
void thread_func(void arg) {
printf("Hello from thread! %d\n", (int)arg);
return NULL;
}
int main() {
pthread_t tid;
int num = 42;
pthread_create(&tid, NULL, thread_func, &num);
pthread_join(tid, NULL); // 等待线程结束
return 0;
}
```
💡 小提示:线程结束后记得用 `pthread_join()` 或 `pthread_detach()` 来释放资源。这样不仅能提高效率,还能避免内存泄漏哦!
😉 多线程编程虽然强大,但也需谨慎使用,避免造成复杂的数据竞争问题。加油探索吧!