为什么线程msg以相反的顺序出现?

时间:2011-12-23 05:33:13

标签: linux pthreads

当我运行此代码时,我以完全相反的顺序获取线程消息。如果我创建线程A和B,则A的msg应首先出现,然后是B.然后,如果我创建一个包含10个线程的数组,则msg应该按顺序打印。如果存在任何同步问题,则msg在所有情况下都不应显示相同的反向行为。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Required for thread APIs */
#include <pthread.h>

#define NTHREADS        10
int counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *print_thread_msg(void *ptr){
        char *message;
        printf("Thread number %ld\n", pthread_self());
        pthread_mutex_lock(&mutex);
        counter++;
        printf("Counter value: %d\n",counter);
        message = (char *) ptr;
        printf("%s \n",message);
        sleep(1);
        pthread_mutex_unlock(&mutex);
        message = (char *) ptr;
        printf("%s \n",message);
}

int main (void){
        pthread_t threadA, threadB;
        pthread_t thread_id[NTHREADS];

        int i,j;

        char *msgA = "I am thread A";
        char *msgB = "I am thread B";

        pthread_create(&threadA, NULL, print_thread_msg, (void *)msgA);
        pthread_create(&threadB, NULL, print_thread_msg, (void *)msgB);

        for(i=0; i<NTHREADS; i++)
               pthread_create(&thread_id[i], NULL, print_thread_msg, (void *)"print_thread_msg");

        pthread_join(threadA, NULL);
        pthread_join(threadB, NULL);

        for(j=0; j < NTHREADS; j++)
                pthread_join(thread_id[j], NULL);

        printf(" Finally Counter Value : %d\n",counter);

        exit(0);
}

1 个答案:

答案 0 :(得分:0)

您的代码正确运行。我尝试了3个线程。它总是从线程A开始,其余的线程随机跟随。您是否尝试在其他系统中运行代码?