-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwin32_thread_queue.c
More file actions
45 lines (38 loc) · 1.06 KB
/
Copy pathwin32_thread_queue.c
File metadata and controls
45 lines (38 loc) · 1.06 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <Windows.h>
#include <stdio.h>
volatile int cursor;
BOOL is_prime[1048576];
BOOL prime(int x) {
if (x == 2)
return TRUE;
if (x <= 1 || !(x % 2))
return FALSE;
for (INT64 i = 3; i * i <= x; i += 2)
if (!(x % i))
return FALSE;
return TRUE;
}
DWORD CALLBACK thread_function(void *param) {
for (;;) {
int index = InterlockedIncrement(&cursor) - 1;
if (index >= _countof(is_prime))
return 0;
is_prime[index] = prime(index);
}
}
int main(void) {
SYSTEM_INFO info;
GetSystemInfo(&info);
HANDLE threads[MAXIMUM_WAIT_OBJECTS];
int num_extra_threads = (int)info.dwNumberOfProcessors - 1;
if (num_extra_threads > _countof(threads))
num_extra_threads = _countof(threads);
printf("Creating %d worker threads.\n", num_extra_threads);
for (int i = 0; i < num_extra_threads; ++i)
threads[i] = CreateThread(NULL, 0, thread_function, NULL, 0, NULL);
thread_function(NULL);
WaitForMultipleObjects((DWORD)num_extra_threads, threads, TRUE, INFINITE);
for (int i = 0; i < _countof(is_prime); ++i)
if (is_prime[i])
printf("%d is prime.\n", i);
}