线程未按正确顺序打印 [英] Thread not printing out in correct order
问题描述
我对 C 中的线程相当陌生.对于这个程序,我需要声明一个线程,我将它传入一个 for 循环,该循环旨在从线程中打印出 printf.
I'm fairly new to threads in C. For this program I need to declare a thread which I pass in a for loop thats meant to print out the printfs from the thread.
我似乎无法按正确顺序打印.这是我的代码:
I can't seem to get it to print in correct order. Here's my code:
#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
推荐答案
这是理解多线程的经典例子.线程并发运行,由操作系统调度程序调度.当我们谈论并行运行时,没有正确顺序"这样的东西.
That's the classic example of understanding multi-threading. The threads are running concurrently, scheduled by OS scheduler. There is no such thing as "correct order" when we are talking about running in parallel.
此外,还有为 stdout 输出刷新缓冲区之类的东西.意思是,当您打印"某些内容时,并不会保证它会立即发生,而是会在达到某个缓冲区限制/超时后发生.
Also, there is such thing as buffers flushing for stdout output. Means, when you "printf" something, it is not promised it will happen immediately, but after reaching some buffer limit/timeout.
另外,如果你想以正确的顺序"完成工作,意味着等到第一个线程完成它的工作再开始下一个,考虑使用加入":http://man7.org/linux/man-pages/man3/pthread_join.3.html
Also, if you want to do the work in the "correct order", means wait until the first thread finishes it's work before staring next one, consider using "join": http://man7.org/linux/man-pages/man3/pthread_join.3.html
更新:在这种情况下,将指针传递给 thread_id 也是不正确的,因为线程可能会打印不属于他的 id(感谢 Kevin)
UPD: passing pointer to thread_id is also incorrect in this case, as a thread may print id that doesn't belong to him (thanks Kevin)
这篇关于线程未按正确顺序打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!