【发布时间】:2016-03-26 19:53:22
【问题描述】:
我正在准备我的 Op sys 课程的期末考试,但我无法理解 pthread。在这段代码中,
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void * action( void * arg ) {
int t = *(int *)arg;
printf( "THREAD %u: I'm alive %d\n", (unsigned int)pthread_self(), t );
sleep( t );
return NULL;
}
int main() {
pthread_t tid[4];
int i, t;
for ( i = 0 ; i < 4 ; i++ ) {
t = 1 + i * 3;
printf( "MAIN: Creating thread for task %d\n", t );
pthread_create( &tid[i], NULL, action, &t );
}
for ( i = 0 ; i < 4 ; i++ ) {
pthread_join( tid[i], NULL );
printf( "MAIN: Joined child thread %u\n", (unsigned int)tid[i] );
}
return 0;
}
对于输出:
MAIN: Creating thread for task 1
MAIN: Creating thread for task 4
THREAD 1845290752: I'm alive 4
MAIN: Creating thread for task 7
THREAD 1836898048: I'm alive 7
MAIN: Creating thread for task 10
THREAD 1828505344: I'm alive 10
THREAD 1820112640: I'm alive 10
MAIN: Joined child thread 1845290752
MAIN: Joined child thread 1836898048
MAIN: Joined child thread 1828505344
MAIN: Joined child thread 1820112640
为什么 THREAD #: I am alive 1 不与其他内容一起打印出来? 这里的执行流程是如何发生的?
【问题讨论】:
-
“这里的执行流程是如何发生的?”很可能是并行的。所有线程都读取 same
t,它会被pthread_create()周围的每次迭代覆盖。三思而后行!
标签: c multithreading unix pthreads