開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
gcc pthread
問題(Question):
一般在 multithread 共用函數時會Lock,
但請教在什麼情況下可以不用 Lock?
或者說在什麼情況下一定要 Lock?
寫了一個 sample 不 Lock 執行不會有錯誤
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_t thread_id_1 = 0;
pthread_t thread_id_2 = 0;
int sum = 0;
void common(int x) {
sum += x;
}
void thread_func_1() {
int i;
for (i = 0; i < 100; i++) {
common(-1);
}
printf("thread1 end\n");
}
void thread_func_2() {
int i;
for (i = 0; i < 100; i++) {
common(1);
}
printf("thread2 end\n");
}
void thread_create_1() {
int rc = 0;
rc = pthread_create(&thread_id_1, NULL, (void *) &thread_func_1, NULL);
if (rc) {
fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc);
return;
}
}
void thread_create_2() {
int rc = 0;
rc = pthread_create(&thread_id_2, NULL, (void *) &thread_func_2, NULL);
if (rc) {
fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc);
return;
}
}
void thread_wait_1() {
if (thread_id_1 != 0) {
pthread_join(thread_id_1, NULL);
printf("thread 1 stopped\n");
}
}
void thread_wait_2() {
if (thread_id_2 != 0) {
pthread_join(thread_id_2, NULL);
printf("thread 2 stopped\n");
}
}
int main(void) {
thread_create_1();
thread_create_2();
thread_wait_1();
thread_wait_2();
printf("sum = %d\n", sum);
return EXIT_SUCCESS;
}