相关疑难解决方法(0)

在为该线程注释pthread_join时多次执行相同的线程子例程

我是线程新手.在这里,如果我评论pthread_join(thread1,NULL),那么在输出中有时我会得到

    Thread2
    Thread1
    Thread1
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么Thread1跟踪会出现两次以及pthread_join的确切功能是什么.

另外,请参考一些关于初学者的线程概念的教程.

    void *print_message_function( void *ptr );
    main()
    {
            pthread_t thread1, thread2;
            char *message1 = "Thread 1";
            char *message2 = "Thread 2";
            int  iret1, iret2;
            iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
            iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
            pthread_join( thread1, NULL);

            pthread_join( thread2, NULL); 

            printf("Thread 1 returns: %d\n",iret1);
            printf("Thread 2 returns: %d\n",iret2);
            exit(0);
    }

    void *print_message_function( void *ptr )
    {
            char *message;
            message = (char *) ptr;
            printf("%s \n", message);
    }
Run Code Online (Sandbox Code Playgroud)

c multithreading pthreads

7
推荐指数
1
解决办法
1310
查看次数

pthread:一个printf语句在子线程中打印两次

这是我的第一个pthread程序,我不知道为什么printf语句在子线程中打印两次:

int x = 1;

void *func(void *p)
{
    x = x + 1;
    printf("tid %ld: x is %d\n", pthread_self(), x);
    return NULL;
}

int main(void)
{
    pthread_t tid;
    pthread_create(&tid, NULL, func, NULL);

    printf("main thread: %ld\n", pthread_self());

    func(NULL);
}
Run Code Online (Sandbox Code Playgroud)

在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU/Linux):

1.
main thread: 140144423188224
tid 140144423188224: x is 2

2.
main thread: 140144423188224
tid 140144423188224: x is 3

3.
main thread: 139716926285568
tid 139716926285568: x is 2
tid 139716918028032: x is 3
tid 139716918028032: x is …
Run Code Online (Sandbox Code Playgroud)

printf pthreads

5
推荐指数
1
解决办法
2930
查看次数

标签 统计

pthreads ×2

c ×1

multithreading ×1

printf ×1