++i和i++都是線程不安全

++i和i++的自加過程:

1、i++

1)將i值取出放到寄存器

2)將寄存器中的值返回

3)寄存器中的值加1

4)使用寄存器值修改i的值

 

2、++i

1)將i值取出放到寄存器

2)寄存器中的值加1

3)將寄存器中的值返回並修改i的值

 

測試代碼如下:

 

#include <stdio.h>
#include <pthread.h>
#include <stdint.h>

uint64_t g_num = 0;

void* thread_fun(void *arg)
{
    printf("thread[%lu]\n", pthread_self());
    int i;
    for (i = 0; i < 1000000000; i++) {
        //g_num++;
        ++g_num;
    }
    printf("thread[%lu] over\n", pthread_self());
    return NULL;
}


int main()
{
    int ret;
    pthread_t thread1, thread2;
    ret = pthread_create(&thread1, NULL, thread_fun, NULL);
    if (ret != 0) {
        printf("thread1 failed!");
    }
    ret = pthread_create(&thread2, NULL, thread_fun, NULL);
    if (ret != 0) {
        printf("thread2 failed!");
    }
    printf("wait\n");
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("g_num = %lu\n", g_num);
    return 0;
}

 

 

測試結果:

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章