- 论坛徽章:
- 4
|
本帖最后由 liuiang 于 2013-01-06 14:17 编辑
本段代码并不能从根本上解决这个问题,所以是错误的,小朋友不要参考~~~~,留下来程序是作为反面教材用的~~~~~~~- #include <stdio.h>
- #include <pthread.h>
- unsigned int cnt;
- unsigned int cnt_bk;
- void * cpu0(void * arg)
- {
- while(1) {
- __asm__ __volatile__(
- "mfence\n\t"
- "incl %0\n\t"
- "mfence"
- : "=m" (cnt)
- : "m" (cnt)
- :"memory");
- }
- }
- void * cpu1(void * arg)
- {
- while(1) {
- sleep(5);
- __asm__ __volatile__("mfence":::"memory");
- cnt_bk = cnt;
- cnt = 0;
- __asm__ __volatile__("mfence":::"memory");
- }
- }
- void * cpu2(void * arg)
- {
- while(1) {
- sleep(5);
- printf("cnt_bk = 0x%08x\n", cnt_bk);
- }
- }
- int main(int argc, char * argv[])
- {
- pthread_t taskId1, taskId2, taskId3;
- pthread_create(&taskId1, NULL, cpu0, NULL);
- pthread_create(&taskId2, NULL, cpu1, NULL);
- pthread_create(&taskId3, NULL, cpu2, NULL);
- void * tret;
- pthread_join(taskId1, &tret);
- pthread_join(taskId2, &tret);
- pthread_join(taskId3, &tret);
- return 0;
- }
复制代码 |
|