Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
thread SleepWakeup and mutex
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//gcc 5.4.0 #include <stdio.h> #include <pthread.h> int x=0, y=1, estado=0, p=0, limite=16; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void *data) { while (x <= y) { /* ... */ while (estado==0){p+=1; if(p>limite){printf("|"); p=0; limite=limite*limite;};} pthread_mutex_lock(&mutex); //Pedir LOCK printf("<(2) THREAD 1, msg antes ativar thread2.>\n"); pthread_cond_signal(&cond); //WAKE UP da thread2, ela após acordará essa printf("<(3) THREAD 1, msg antes de ser bloqueada.>\n"); /* Interrompe a thread até receber um 'sinal'! */ pthread_cond_wait(&cond, &mutex); //SLEEP /* ... */ } printf("<(7) THREAD 1, fim;>\n"); pthread_mutex_unlock(&mutex); return NULL; } void *thread2(void *data) { pthread_mutex_lock(&mutex); //Importante bloquear a mudança do estado e dormir, // senão pode acontecer de mudar o estado e antes de dormir, a outra // thread tentar acordar essa, e quando essa estiver dormindo, não ser acordada. estado=1; printf("<(1) THREAD 2, sleep>\n"); pthread_cond_wait(&cond, &mutex); //Dormir para esperar a thread1 entrar no while e imprimir na tela printf("<(4) THREAD 2, wake>\n"); //pthread_mutex_lock(&mutex); /* ... */ printf("<(5) THREAD 2, lock.>\n"); x = y + 1; pthread_cond_signal(&cond); //WAKE UP da thread1 printf("<(6) THREAD 2, libera 1.>\n"); /* ... */ pthread_mutex_unlock(&mutex); return NULL; } int main(){ pthread_t tid1; pthread_t tid2; pthread_create(&tid2, NULL, thread2, NULL); pthread_create(&tid1, NULL, thread1, NULL); printf("{\n"); sleep(9); printf("}\n"); }
gcc
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.13 sec, absolute running time: 9.07 sec, cpu time: 4.57 sec, memory peak: 3 Mb, absolute service time: 9,29 sec
edit mode
|
history
|
discussion