原版
worker
內有兩個 fprintf
在多執行緒情境下無法保證第一個執行完後馬上換下一個。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| #include <stdio.h>
#include <omp.h>
void worker(const char * message) {
int tid = omp_get_thread_num();
fprintf(stdout, "worker %d: ", tid);
fprintf(stdout, "do %s\n", message);
}
int main(void) {
omp_set_num_threads(4);
#pragma omp parallel for
for (int i = 0; i < 100; ++i) {
char message[8];
snprintf(message, 8, "task %d", i);
worker(message);
}
return 0;
}
|
$ gcc -o flockfile_test -fopenmp flockfile_test.c
$ ./flockfile_test >|out.txt
利用 flockfile 達成預期效果
要記得 unlock。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| #include <stdio.h>
#include <omp.h>
void worker(const char * message) {
int tid = omp_get_thread_num();
flockfile(stdout);
fprintf(stdout, "worker %d: ", tid);
fprintf(stdout, "do %s\n", message);
funlockfile(stdout);
}
int main(void) {
omp_set_num_threads(4);
#pragma omp parallel for
for (int i = 0; i < 100; ++i) {
char message[8];
snprintf(message, 8, "task %d", i);
worker(message);
}
return 0;
}
|
References