[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

thread programm question



Hi!

Извиняюсь за offtopic, но может кто сможет объяснить мне следующее:
есть, например, такая программа: (Собственно вопрос в комметарии в
теле программы. Ядро 2.4.8, если это важно).

#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

sem_t semaphore;

void err_abort(int code, const char* text)
{
    fprintf(stderr,"%s at \"%s\":%d: %s\n",text, __FILE__, __LINE__, 
	    strerror(code));
    abort ();
}
	    
void errno_abort(const char* text)
{
    fprintf (stderr, "%s at \"%s\":%d: %s\n",text, __FILE__, __LINE__, 
	    strerror (errno));
    abort ();
}

void *run(void *arg)
{
    int num = *((int*)(arg));

    fprintf(stderr,"Thread %i\n", num);
    if (sem_wait(&semaphore) == -1)
        errno_abort ("Wait on semaphore");
    fprintf(stderr,"Thread %d resuming\n", num);
    return NULL;
}

int main (int argc, char *argv[])
{
    int thread_count;
    pthread_t sem_waiters[5];
    int status;

    if (sem_init (&semaphore, 0, 0) == -1)
        errno_abort ("Init semaphore");

    for (thread_count = 0; thread_count < 5; thread_count++) {
        status = pthread_create (
            &sem_waiters[thread_count], NULL,run,&thread_count);
	sleep(1);
	/* Если мы имеем вышестоящую строчку закоментрированной,
	то получаем такой вывод:

              Thread 1
              Thread 2 <------ ????
              Thread 2 <------ ????
              Thread 4
              Thread 5
              Posting from main: 0
              Posting from main: 0
              Posting from main: 0
              Posting from main: 0
              Posting from main: 0
              Posting from main: 0
              Thread 1 resuming
              Thread 2 resuming
              Thread 2 resuming
              Thread 4 resuming
              Thread 5 resuming

	Если же мы ее раскомментируем, то все работает как и должно
	по идее. Т.е. вывод такой

		Thread 0
		Thread 1
		Thread 2
		Thread 3
		Thread 4
		Posting from main: 0
		Posting from main: 0
		Posting from main: 0
		Posting from main: 0
		Posting from main: 0
		Posting from main: 0
		Thread 0 resuming
		Thread 2 resuming
		Thread 1 resuming
		Thread 3 resuming
		Thread 4 resuming

	Может кто объяснит мне что происходит и как избегать таких 
	хаков со sleep().
	
	*/      
        if (status != 0)
            err_abort (status, "Create thread");
    }

    sleep(1);

    while (1) {
        int sem_value;

        if (sem_getvalue(&semaphore, &sem_value) == -1)
            errno_abort ("Get semaphore value");
        if (sem_value > 0) break;
        fprintf (stderr,"Posting from main: %d\n", sem_value);
        if (sem_post (&semaphore) == -1)
            errno_abort ("Post semaphore");
    }

    for (thread_count = 0; thread_count < 5; thread_count++) {
        status = pthread_join (sem_waiters[thread_count], NULL);
        if (status != 0)
            err_abort (status, "Join thread");
    }
    return 0;
}
-- 
WBR, Konstantin V. Sorokin
:wq



Reply to: