【问题标题】:C code multithreading PthreadC代码多线程Pthread
【发布时间】: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


【解决方案1】:

为什么 THREAD #: I'm alive 1 不与其余部分一起打印出来?

因为t一个位置。通过

    pthread_create( &tid[i], NULL, action, &t );

当子线程到达时

    int t = *(int *)arg;

主线程可以更改将地址传递给子线程的t 的值。

希望本练习的重点是确定这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2016-03-06
    • 2011-05-12
    相关资源
    最近更新 更多