🌟linux pthread_create()函数用法🌟

导读 在Linux系统中,`pthread_create()` 是线程编程中的重要函数之一,用于创建一个新的线程。它的原型如下:`int pthread_create(pthread_t...

在Linux系统中,`pthread_create()` 是线程编程中的重要函数之一,用于创建一个新的线程。它的原型如下:`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

void thread_func(void arg) {

printf("Hello from thread! %d\n", (int)arg);

return NULL;

}

int main() {

pthread_t thread_id;

int num = 42;

pthread_create(&thread_id, NULL, thread_func, &num);

pthread_join(thread_id, NULL);

return 0;

}

```

运行后会看到子线程打印出 "Hello from thread!" 和传入的数值。掌握 `pthread_create()` 的使用,是实现多线程编程的基础,让程序并发执行提高效率!🚀

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时候联系我们修改或删除,多谢。