venuswu
venuswu

Reputation: 107

The calling sequence of pthread_init pthread_lock, pthread_destroy and so on?

Normally, the correct sequence is something like this:

pthread_mutex_init(&mutex,NULL);

pthread_mutex_lock(&mutex);

pthread_mutex_unlock(&mutex);

pthread_mutex_destroy(&mutex);

mutex should be initialized first, and then pthread_mutex_lock and pthread_mutex_unlock can be called in respective thread to protect the critical section, finally pthread_mutex_destroy is called to destroy the mutex after the completion of all threads. But if the order is mixed, What would happend?

I disrupt the sequence of the functions in order to find out the error, but everything seems normal when the sequence is messed in different way. Here is an example.

pthread_mutex_t mutex;
static int count = 0;

void* func(void* arg)
{
    pthread_mutex_lock(&mutex);
    *(int*)arg = *(int*)(arg) + 1;
    printf("thread %d\n", *(int*)arg);
    pthread_mutex_unlock(&mutex);
}

int main(int argc, char* argv[])
{
    int i;
    pthread_mutex_init(&mutex, NULL);

    pthread_mutex_destroy(&mutex);

    for(i = 0; i < 3; i++)
    {
        pthread_t tid;
        pthread_create(&tid, NULL, func, (void*)(&count));
        sleep(5);
    }

    printf("the main thread exit normally.\n");
}

I want to ask whether the sequence matters to the program. Is there something inside the function to assure the calling sequence, or something else? If these functions can be used without order, why should pthread_mutex_init() and pthread_mutex_destroy() be defined?

Upvotes: 2

Views: 7939

Answers (1)

janneb
janneb

Reputation: 37188

What happens is undefined behavior. The implementation may, or may not, print an error, abort the program, or start WW III. Or it may appear to work just fine, but there are no guarantees.

Upvotes: 4

Related Questions