gpt4 book ai didi

C线程只运行一次

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:10 24 4
gpt4 key购买 nike

我想在单个进程中并行运行一些作业。由于某种原因,我创建的线程只运行一次,请帮助我了解我的错误在哪里。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void * print_thread (void * var)
{
int *p_var = (int *)var;
printf("this is a thread %d\n", ++(*p_var));

}

int main()
{
int x=0;
pthread_t thread1;


if(pthread_create(&thread1, NULL, print_thread, &x))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}

while (1)
{
usleep(100000);
}

return 0;
}


# gcc -o thread pthread_example.c -lpthread
# ./thread
this is a thread 1

最佳答案

您应该将 print_thread 视为您的新线程“主要”。它将从开始运行到结束,然后线程将退出。除非您在 print_thread 内部有某种循环,否则它永远不会持续存在。

关于C线程只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43365376/

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