gpt4 book ai didi

c - 运行时线程创建

转载 作者:行者123 更新时间:2023-11-30 20:16:26 25 4
gpt4 key购买 nike

在运行时,如何创建线程?

我将从标准输入终端获取线程数,然后根据这个数字创建线程。但是,如何?

Ex: 
input : N, N is integer

in main function

create N thread

编辑:Linux 平台

最佳答案

是的,线程(如果我们假设我们使用的是 pthread)是通过调用 pthread_create 创建的,您可以从循环中调用它。

下面是创建 N 个线程的 C 函数的开头:

int start_N_threads(int N) {
pthread_t threads[N];
printf("Starting %d thread(s)...\n", N);
for (int i = 0; i < N; ++i) {
if (pthread_create(&threads[i], NULL, thread_body, (void*)&results[i]) != 0) {
printf("Couldn't create thread %d.\n", i);
}
}
printf("The %d thread(s) are running.\n", N);

关于c - 运行时线程创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10276362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com