How to synchronize threads without blocking?

Now, as far as I know, the mutex is used to synchronize the entire thread that uses the same data, following the principle that when one thread uses this data, all other threads should be blocked when using this shared resource until it is unlocked .. Recently, on a blog, I saw code explaining this concept, and some people wrote that blocking all threads while one thread is accessing resources is a very bad idea, and this contradicts the concept of streaming, which is somehow true. . T GDS my question is how to synchronize threads without locking?

Here is the link of this blog

http://www.thegeekstuff.com/2012/05/c-mutex-examples/

+4
source share
5 answers

You cannot synchronize streams without blocking by the synchronization definition itself. However, a good synchronization technique limits the amount of lock to an absolute minimum. To illustrate and indicate exactly why the article is incorrect, pay attention to the following:

From the article:

pthread_t tid[2];
int counter;
pthread_mutex_t lock;

void* doSomeThing(void *arg)
{
    pthread_mutex_lock(&lock);

    unsigned long i = 0;
    counter += 1;
    printf("\n Job %d started\n", counter);

    for(i=0; i<(0xFFFFFFFF);i++);

    printf("\n Job %d finished\n", counter);

    pthread_mutex_unlock(&lock);

    return NULL;
}

What it should be:

pthread_t tid[2];
int counter;
pthread_mutex_t lock;

void* doSomeThing(void *arg)
{
    unsigned long i = 0;

    pthread_mutex_lock(&lock);
    counter += 1;
    int myJobNumber = counter;
    pthread_mutex_unlock(&lock);

    printf("\n Job %d started\n", myJobNumber);

    for(i=0; i<(0xFFFFFFFF);i++);

    printf("\n Job %d finished\n", myJobNumber);

    return NULL;
}

, ( ), . , . , , counter. , , .

Mutex , , 1 , , . , 1 , 2 - , .

+2

, , .

, , , .

. , MSVC _ Interlocked * .

+1

, , , , -

. , . , , - , .

, , , :

  • , , . .

  • , (, ). .

, , . (, ) . 99% , C.

+1

pthread_mutex_trylock() . , , . , , , - . , , , .. - . , , .

0

, , .

  • . , , - . - , - , -.
  • -Callbacks. . , , . , , , . , heaver, , . , , .

Even with these tools, you can never completely remove the need for some synchronization (counters come to mind).

0
source

Source: https://habr.com/ru/post/1607673/


All Articles