++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;
}
测试结果: