关于同时读写变量的问题:
- Saingel :不一定,要看哪种了,stdstring那种随写入操作而内存位置或大小变更的对象肯定会有问题,如果是在固定的内存上写,不写出界基本没问题,最多运算结果会错
//Sample 同时读写变量
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
void * pp( void * arg)
{
while (1) {
//printf("%s\n", (char *)arg);
int nNum = *((int*)arg);
printf("%d\n", nNum);
sleep(1);
}
return NULL;
}
void * pp22( void * arg)
{
while (1) {
++(*((int*)arg));
sleep(1);
}
return NULL;
}
main()
{
pthread_t pid, pid2;
//char buff[26] = {0};
//strcpy(buff, "hello world");
//pthread_create(&pid, NULL, pp, buff);
int nnumber = 0;
pthread_create(&pid, NULL, pp, &nnumber);
pthread_create(&pid2, NULL, pp22, &nnumber);
while (1) {
//printf("I am main thread\n");
++nnumber;
sleep(1);
}
}
以上代码确实能正常运行。