参考文章:Linux C语言 多线程竞争实例以及简单解决办法
线程在短时间内对相同内存单元进行操作时,如果不加锁解锁,有可能产生线程竞争的情况,即最终结果不符合预期
示例:
test_pthread_compete.c
#include#include #include #include static long unsigned int count = 0; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; static void *funcAdd(void *arg){ pthread_mutex_lock(&mylock); count++; pthread_mutex_unlock(&mylock); sleep(1); pthread_mutex_lock(&mylock); count++; pthread_mutex_unlock(&mylock); sleep(1); pthread_mutex_lock(&mylock); count++; pthread_mutex_unlock(&mylock); pthread_exit(NULL); } static void *funcAdd_nolock(void *arg){ count++; sleep(1); count++; sleep(1); count++; pthread_exit(NULL); } int main(){ pthread_t tid[1024]; int i, j; //不加锁 for(i = 0; i < 1000; i++){ if(pthread_create(&tid[i], NULL, funcAdd_nolock, NULL) != 0){ perror("pthread_create()"); //for(j = 0; j < i; j++){ // pthread_join(tid[i], NULL); //} } } for(i = 0; i < 1000; i++){ pthread_join(tid[i], NULL); } printf("if without lock, count = %ldn", count); count = 0; //加锁 for(i = 0; i < 1000; i++){ if(pthread_create(&tid[i], NULL, funcAdd, NULL) != 0){ perror("pthread_create()"); //for(j = 0; j < i; j++){ // pthread_join(tid[i], NULL); //} } } for(i = 0; i < 1000; i++){ pthread_join(tid[i], NULL); } printf("if has lock, count = %ldn", count); exit(0); }
ubuntu上编译:
gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo && ./test_pthread_compete
运行结果:
[root@ubuntu /arnold_test/20220721_test_pthread]15# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo && ./test_pthread_compete if without lock, count = 2935 if has lock, count = 3000 [root@ubuntu /arnold_test/20220721_test_pthread]16# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo && ./test_pthread_compete if without lock, count = 2935 if has lock, count = 3000 [root@ubuntu /arnold_test/20220721_test_pthread]17# gcc test_pthread_compete.c -lpthread -o test_pthread_compete && echo && ./test_pthread_compete if without lock, count = 2943 if has lock, count = 3000



