¿Cómo pausar la ejecución entre hilos?

I'm learning thread synchronization and this is the demo to show how to lock critical data when a thread is executing:

http://ideone.com/7Do0l (To run this code, compile it with the -pthread parameter in Linux/MacOS environment)

The program works as expected, but the sleep() function doesn't pause the execution between threads. My idea is to have one thread do the calculation at a time, then 1 second later another thread comes into play. Here is the code segment I'm fighting with:

while(1) {
        //sleep(1);     //(1) (Sleep for one second)
        sem_wait(&mutex);
        //sleep(1);     //(2)
                printf("Thread #%d is doing math. %d + 1 = %d.\n", (int) id, s, s+1);
                s++;
        //sleep(1);     //(3)
        sem_post(&mutex);
        //sleep(1);     //(4)
}

There are four positions I have tried to put the sleep() in. (1) and (4) result in no pauses between single threads but between two bunches of ten threads. (2) and (3) result in one thread gets executed repeatedly for very long time before another gets called.

Is there a remedy to this?

Noticias

There is a trick to make the program produce the result: generating the sleeping time randomly for each thread, but it's not consistent since two random numbers could be the same by accident.

preguntado el 24 de agosto de 12 a las 05:08

What exactly are you trying to accomplish? What is the behavior you would expect? -

Debe ser como: Thread #1 is doing math. 1 + 1 = 2. (Then 1 second later:) Thread #2 is doing math. 2 + 1 = 3. (And so on) -

Am I the only one noticing that people here are referencing 1 millisecond as 1 second and in answer below 100 milliseconds as 1 second. -

Don't call a semaphore mutex. -

@Abhineet the sleep() function in Linux is in seconds, while the equivalent Sleep() (uppercase S) in Windows is in milliseconds. -

3 Respuestas

Put it in the 3rd position, since you want a one second delay between printf mensajes.

If you want to make sure that all threads are initialized before any of them can enter into the critical section, modify the main function of the linked code to this

int main() {
    pthread_t thread[10];

    int i;
    sem_init(&mutex, 0, 1);
    sem_wait(&mutex);
    for (i = 0; i<10; ++i)
            pthread_create(&(thread[i]), NULL, job, (void*) i);
    sem_post(&mutex);
    sleep(100);
}

Respondido 24 ago 12, 05:08

I tried that many times, (2) and (3) result in the same behaviour: One thread getting executed repeatedly. - Max

So what output do you expect? - adib saad

Thanks for the code, I've just tried but it works in exactly the same way. You'll see the whole bunch of ten threads get executed at the same time, then a pause, then another bunch of ten threads.... As for the expected output, I have made it clear twice above... - Max

Putting it in the 3rd position produces the output you described: Thread #1 is doing math. 1 + 1 = 2., (1s delay), Thread #2 is doing math. 2 + 1 = 3., (1s delay), Thread #3 is doing math. 3 + 1 = 4. Etc.- adib saad

Here is the result produced by my computer, using Linux, with themain() function replaced by yours and the sleep() function in the 3rd place: Thread #1 is doing math. 0 + 1 = 1. Thread #1 is doing math. 1 + 1 = 2. Thread #1 is doing math. 2 + 1 = 3. Thread #1 is doing math. 3 + 1 = 4. And so on... My previous comment was wrong: in the (2) and (3) position, the sleep() results in one thread getting executed repeatedly. - Max

That's not really the kind of problem threads are designed to solve. You'd have to have a separate semaphore for each thread, have one thread loop through those, calling sem_post on a different one each second, and the rest just calling sem_wait. May as well just use the one thread.

Respondido 24 ago 12, 06:08

I believe there is a solution because this small program is a prototype of what I have to do in my next assignment. I have to somehow manage to get hundreds of similar threads executing their part in turn using only several semaphores to control. - Max

I did some research and found that the only way to produce the desired output is the one I mentioned in the Noticias part. That is, instead of hard coded the sleep timer, just give each thread a random number:

    // Sleep time in microseconds.
    int st = rand() % 500000;
    usleep(st);

And actually I have been over-worrying about two threads doing the same thing at once. Even though the two adjacent random timers could be accidentally the same, two threads never get executed on the same core of the CPU at the same time, in case the CPU is of multiple cores, no two instructions can modify the same memory content concurrently.

Respondido 24 ago 12, 09:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.