pthread_create

linux的pthread_create函数怎么使用

小亿
93
2023-07-06 15:43:26
栏目: 编程语言

pthread_create函数用于创建一个新的线程。

函数原型如下:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

参数说明:

下面是一个简单的示例代码,展示了如何使用pthread_create函数创建一个新的线程:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg) {
int thread_arg = *(int*)arg;
printf("Hello from thread! Argument: %d\n", thread_arg);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int arg = 123;
int result = pthread_create(&thread, NULL, thread_function, &arg);
if (result != 0) {
printf("Error creating thread.\n");
return 1;
}
printf("Hello from main thread!\n");
pthread_join(thread, NULL);
return 0;
}

在上面的示例代码中,创建了一个新的线程,并将参数123传递给线程启动函数thread_function。主线程打印一条消息后,调用pthread_join函数等待新线程执行完毕。

0
看了该问题的人还看了