c语言线程是怎么传int类型的参数,举个例子
时间: 2023-06-04 09:07:48 浏览: 59
感谢您的问题。关于C语言中线程传递int类型参数的方法,可以通过将参数作为一个指针传递给线程函数来实现。下面是一个简单的例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_func(void* arg) {
int num = *(int*)arg;
printf("Thread received number: %d\n", num);
return NULL;
}
int main() {
pthread_t thread_id;
int num = 42;
if (pthread_create(&thread_id, NULL, thread_func, &num) != 0) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
if (pthread_join(thread_id, NULL) != 0) {
fprintf(stderr, "Error joining thread\n");
return 1;
}
return 0;
}
```
在上面的例子中,我们定义了一个整型变量num,并通过取其地址来创建线程。然后在线程函数中,我们将参数指针强制转换为int类型,并将其值存储在一个新的变量num中,然后打印输出。
希望这个例子能够帮助您理解如何在C语言中传递int类型的参数给线程函数。