【问题标题】:C Threaded while loop not runningC线程的while循环未运行
【发布时间】:2021-09-14 13:19:41
【问题描述】:

我想要一个线程化的while 循环,该循环永远递增i。为什么会过早停止?

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

void *increment () {
    int i = 0;
    while (1) {
        i++;
        printf("Number: %d", i);
    }
}

int main (int argc, char **argv) {
    if (argc <= 1) {
        fprintf(stderr, "Invalid params\n");
        exit(-1);
    }

    int num_threads = atoi(argv[1]);
    pthread_t thread[num_threads];

    for (int i = 0; i < num_threads; i++) {
        pthread_create(&thread[i], NULL, &increment, argv[1]);
    }

    return 0;
}

【问题讨论】:

  • 您需要等待线程完成,然后再从 main 返回。查看pthread_join
  • 另外,您的函数 increment 未正确声明。应该是void *increment(void *arg); 你没有收到编译器警告吗?
  • 扩展@MFisherKDX 的评论:退出或终止进程应该终止所有正在运行的线程。
  • increment 缺少return NULL
  • @MFisherKDX 感谢您的帮助,我设法让它工作。抱歉我的回复晚了

标签: c pthreads


【解决方案1】:

随便放

while(1);

如果您只想让创建的线程永远运行,则在 main 中返回之前

例如

int main (int argc, char **argv) {
    if (argc <= 1) {
        fprintf(stderr, "Invalid params\n");
        exit(-1);
    }

    int num_threads = atoi(argv[1]);
    pthread_t thread[num_threads];

    for (int i = 0; i < num_threads; i++) {
        pthread_create(&thread[i], NULL, &increment, argv[1]);
    }

    while(1) ; // don't exit the main thread

    // while (1) sleep(1000) ; // would be better

    return 0;
}

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2020-03-06
    • 2021-10-26
    • 2022-01-02
    • 1970-01-01
    • 2015-06-14
    相关资源
    最近更新 更多