c-while循环从两个不同的pthread读取相同的变量,但代码没有运行



我正在尝试检测简单内存共享中的核心到核心延迟。我的目标是从两个不同的线程读取全局变量。假设变量一开始是x=0。现在,一个线程将读取该值并将x更改为1。另一个线程正在读取相同的变量,一旦它读取到x=1,它就会将其设为0。我已经写了以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
double getsecs(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1.0e6;
}
int x=0;
//count=0;
void* changetoone(void *arg)
{
//sched_setaffinity(0);
for (int i=0; i<10000; i++){
while(x!=1)
{ 
x=1;
printf("%d", x);
}
}
return 0;
}
void* changetozero(void *arg){
//sched_setaffinity(5);
for (int i=0; i<10000; i++){
while(x!=0)
{ 
x=0;
printf("%d", x);
}
} 
return 0;           
} 
int main()
{
pthread_t thread1;
pthread_create(&thread1, NULL, changetoone, &x);
pthread_t thread2;
pthread_create(&thread2, NULL, changetozero, &x);    
pthread_join(&thread1, NULL);
pthread_join(&thread2, NULL);
}

由于某种原因,代码没有运行。我不熟悉使用pthread,我想我犯了一些愚蠢的错误。有人能帮我指出错误吗?

pthread_join的第一个参数是pthread_t,而不是pthread_t*。所以在调用它时不应该使用&

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

由于访问x时线程之间缺乏同步,因此程序的实际行为未定义。但这至少会允许线程运行。

最新更新