C线程只运行一次

标签 c pthreads

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

#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/

相关文章:

c - fread() 总是返回 1 的问题

android - Linux 2.6内核进程管理

initialization - pthread_mutex_t 初始化错误

c - 检测 Windows shell 更改

c - 双缓冲设计I/O同步

c - 多线程 Web 服务器的线程池

c++ - 清除同步概念的小项目想法

C中十进制转二进制

c++ - 预处理器定义重复

c - Linux 中的 getch() 和 getche() 等价于什么?