1、数据混乱:
多个线程操作共享数据
CPU调度问题
2、
如何解决
线程同步:协同步调,按照先后顺序执行操作
1、
数数
是CPU来数数,存到寄存器里面,CPU能数的数据量比较小
寄存器需要和物理内存实时做数据交换
取数据的值时
在物理内存中取值
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<pthread.h>
#define MAX 10000
int number;
void* funcA_num(void* arg)
{
for(int i = 0; i < MAX; i++)
{
number++;
printf("thread A, id = %lu, number = %d\n", pthread_self(), number);
usleep(10);
}
}
void* funcB_num(void* arg)
{
for(int i = 0; i < MAX; i++)
{
number++;
printf("thread B, id = %lu, number = %d\n", pthread_self(), number);
usleep(10);
}
}
int main(int argc, const char* argv[])
{
pthread_t p1,p2;
pthread_create(&p1, NULL, funcA_num, NULL);
pthread_create(&p2, NULL, funcB_num, NULL);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
return 0;
}
2、
丢了几个数据
其实是被覆盖了