S
S
sebastian2011-10-19 12:08:02
C++ / C#
sebastian, 2011-10-19 12:08:02

Connoisseurs of C and mutex?

We have a code

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

int var = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;

void * increment() 
{
    while(1)
    {   
        pthread_mutex_lock(&lock);
        ++var;
        pthread_mutex_unlock(&lock);
        pthread_cond_signal(&cond);
//        sleep(1);
    }
}

void * _print()
{
    while(1)
    {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond,&lock);
        printf("%d\n", var);
        pthread_mutex_unlock(&lock);
    }



}

int main()
{
    pthread_t th1, th2, th3;
    pthread_create(&th1,NULL,increment, NULL);
    pthread_create(&th2,NULL,_print,NULL);

    pthread_join(th2,NULL);
    pthread_join(th1,NULL);
    return 0;

}

What behavior can be expected from the program depending on the processor (architecture, number of cores)?
Examples of output chunks on different processors:
Times (intel pentium 4 2 cores):
498770
498771
498772
498773
498774
498775
498776
498777
498778
498779
498780
498781
! It is important that the numbers are in order.
Two (intel core 2 duo):
8413753
8413817
8413880
8413943
8414006
8414067
8414129
8414192
8414259
8414322
8414384
Very big dips.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
T
TheHorse, 2011-10-19
@TheHorse

Well, there must be failures. ++ is much easier than a print, and in one unit of time it is performed much more often ... Cond can be removed, it seems to be superfluous here.
On the ancient process, everything goes synchronously, probably because the locking operations are much more complicated than ++ and print, which is why it switches contexts after each operation on the mutex ...

S
sebastian, 2011-10-19
@sebastian

But that's what the mutex is for, so that everything is in order.

M
mark_ablov, 2011-10-19
@mark_ablov

the mutexes in the example only ensure that var++ and print(var) are not executed in parallel, they do not provide order in any way in this example.

T
tangro, 2011-10-19
@tangro

The event will really help you better

D
desenix, 2011-10-19
@desenix

You probably need a semaphore, read Multithreading and Synchronization.

A semaphore is designed to limit the maximum number of threads that can work on a resource at the same time.

Or, as already noted here Event (event).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question