Professional Documents
Culture Documents
2 Threading Main - Key
2 Threading Main - Key
Skill 1: threading
no difficult barriers to
cross
f1(…) f2(…)
shared data { {
process
… …
easy parallelism } }
multi-core, multi-CPU,
symmetric, asymmetric
threads = « light proc. »
2
First In First Out scheduling (FIFO)
q > t(P3)
3 context
P1 P2 P3
changes
q = t(P2)
5 context
P1 P2 P3 P1 P3
changes
q < t(P2)
9 context
P1 P2 P3 P1 P2 P3 P1 P3 P3
changes
4
symmetrical
thread1 … threadN
multi-core/CPU :
OS
OS core1 … coreN
asymmetrical
thread1 … threadN
multi-core/CPU :
OS
master : OS
core1 core2 … coreN
slaves : master
POSIX
pthread_create
pthread_detach
f() f()
pthread_join
leaves the thread
alone
waits for the result
of a thread
6
Windows
CreateThread
CloseHandle
f() f()
WaitForSingleObject
CloseHandle leaves the thread
alone
waits for the result
of a thread
exclusive release
acquisition of the resource
of a resource
locking unlocking
9
thread1|2
thread2|1
POSIX
void *function(void *data)
{
pthread_mutex_t *mutex = (pthread_mutex_t*)data;
pthread_mutex_lock(mutex);
puts("Starting a print job"); fflush(stdout);
sleep(3);
puts("End of the print job"); fflush(stdout);
pthread_mutex_unlock(mutex);
return NULL;
} 10
int main(void)
{
pthread_t thread1;
pthread_t thread2;
pthread_mutex_t lock;
pthread_mutex_destroy(&lock);
return 0;
}
POSIX
11
pthread_mutex_lock(mutex); pthread_mutex_lock(mutex)...
puts("Starting a print job"); ...
sleep(3); ...
puts("End of the print job"); ...
pthread_mutex_unlock(mutex); ...;
puts("Starting a print job");
sleep(3);
puts("End of the print job");
pthread_mutex_unlock(mutex);
12
Mutex : deadlock…
1
mutex 1 4
thread 1
thread 2
3
mutex 2 2
13
Condition variable
pthread_mutex_lock
POSIX pthread_mutex_t pthread_mutex_unlock
mutex
condition
variable
pthread_cond_wait
pthread_cond_timedwait pthread_cond_t
pthread_cond_signal
pthread_cond_broadcast
14
mutex
POSIX condition
variable
15
mutex
POSIX condition
variable
16
mutex
POSIX condition
variable
17
Condition variable
EnterCriticalSection
Vista+ CRITICAL_SECTION LeaveCriticalSection
mutex
condition
variable
SleepConditionVariableCS
WakeConditionVariable CONDITION_VARIABLE
WakeAllConditionVariable
18
mutex
Vista+ condition
variable
19
mutex
Vista+ condition
variable
20
mutex
Vista+ condition
variable
21
Semaphore
semaphore
wait
counter
queue
continue continue
23
…
P(sem) ask a token
use the
resource
V(sem) free the token
…
24
counter
≥0 <0
counter = resources still |counter| = waiting
available threads/processes
Initial value :
≥ 1 : resource sharing ;
= 1 : acts like a mutex ;
= 0 : synchronization tool : « consumer thread »
awaits (P), « producer thread » signals (V) :
P consumes P consumes P
produces V produces V …
25