Download c source code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
main:
	// How many threads have arrived to the barrier
	shared count := 0
	// Protects the increment of the count
	shared mutex := semaphore(1)
	// Locked (0) until all threads arrive, then it is unlocked (1)
	shared barrier := semaphore(0)

	// Create arbitrary amount of threads
	shared thread_count := read_integer()
	create_thread(secondary, thread_count)

secondary:
	Statement A

	// Barrier
	wait(mutex)
	// If this is the last thread that reaches the barrier
	if ++count = thread_count:
		while count > 0:
			--count
			signal(barrier)
	signal(mutex)

	wait(barrier)

	// Statement B must be executed until
	// all threads have executed Statement A
	Statement B