[问题] multi-thread 共用函数的问题

楼主: cris122 (总是很多心事)   2016-01-21 11:22:39
开发平台(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;
}
作者: stupid0319 (征女友)   2016-01-21 12:05:00
等碰到BUG时就是Lock的时机!!!
作者: Caesar08 (Caesar)   2016-01-21 12:09:00
当多个thread对同个object执行任何改变状态的操作时例如说sum就应该要是atomic才行因为你这边只是单纯++--,所以不会有错误但你sum最后的值不一定是0顺带一提,C11与C++11都有thread支援,没必要的话,不需使用pthread更正我第一句: 当多个thread"可能同时"对同个object执行任何改变状态的操作时
作者: IKAFIRE (没有)   2016-01-21 12:27:00
不是不爆只是时候未到
作者: hichcock (快乐一整年 ^^~~~)   2016-01-21 13:08:00
推一楼
作者: Clangpp (Clang++)   2016-01-21 13:45:00
基本上存取变更会遇到 但是要看他的值是不会
作者: longlongint (华哥尔)   2016-01-21 17:07:00
执行一亿次试试看啊
作者: littleshan (我要加入剑道社!)   2016-01-21 18:27:00
即使只有一个thread写入,只要有其它thread读取都有很高的机会造成race condition
作者: kwk22   2016-01-22 06:38:00
推1F, 很低的机率遇到core dump时就会知道要lock了...XD
作者: saxontai (黑暗,点缀孤零零的星)   2016-01-22 12:14:00
C11的thread library有实作品了吗?@@
作者: ah7675 (阿毛)   2016-01-24 17:00:00
先去学完作业系统再回来写

Links booklink

Contact Us: admin [ a t ] ucptt.com