【问题标题】:Thread not printing out in correct order线程未按正确顺序打印
【发布时间】:2016-09-30 19:44:17
【问题描述】:

我对 C 中的线程相当陌生。对于这个程序,我需要声明一个线程,我在 for 循环中传递该线程,以便从线程中打印出 printfs。

我似乎无法让它以正确的顺序打印。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 16

void *thread(void *thread_id) {
    int id = *((int *) thread_id);
    printf("Hello from thread %d\n", id);
    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
        int code = pthread_create(&threads[i], NULL, thread, &i);

        if (code != 0) {
            fprintf(stderr, "pthread_create failed!\n");
            return EXIT_FAILURE;
        }
    }
    return EXIT_SUCCESS;
}

//gcc -o main main.c -lpthread

【问题讨论】:

标签: c pthreads


【解决方案1】:

这是理解多线程的经典例子。 线程同时运行,由 OS 调度程序调度。 当我们谈论并行运行时,没有所谓的“正确顺序”。

此外,还有为 stdout 输出刷新缓冲区之类的东西。意味着,当您“打印”某些内容时,并没有承诺它会立即发生,而是在达到某个缓冲区限制/超时之后。

另外,如果你想以“正确的顺序”完成工作,意味着等到第一个线程完成它的工作后再开始下一个,考虑使用“join”: http://man7.org/linux/man-pages/man3/pthread_join.3.html

更新: 在这种情况下,将指针传递给 thread_id 也是不正确的,因为线程可能会打印不属于他的 id(感谢 Kevin)

【讨论】:

  • 那么它以随机顺序打印就可以了吗?我假设我在函数参数中传递的“i”值有问题。
  • 是的,这将是您的常见行为。如果您愿意,请尝试使用“加入”技术(这将不再是并行的)
  • 我添加了“(void) pthread_join(threads[i], NULL);”在“int code = ...”之后,它起作用了!非常感谢埃里克。
  • 请注意,您的线程都有一个指向同一个int 的指针。如果您不使用join,您可能会得到多个线程打印出相同的 id 值。
  • Kevin 是正确的,您可以考虑按值传递 i,这也可能是看到“错误顺序”的原因(假设较早启动的线程打印在下一个线程启动之前,如果没有也不会承诺加入)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多