C while循环从2个不同的pthread读取相同的变量,但代码未运行

C while循环从2个不同的pthread读取相同的变量,但代码未运行,c,linux,while-loop,pthreads,C,Linux,While Loop,Pthreads,我试图检测简单内存共享中的核心到核心延迟。我的目标是从两个不同的线程读取全局变量。假设变量开始时为x=0。现在,一个线程将读取该值并将x更改为1。另一个线程正在读取相同的变量,当它读取x=1时,它将使其为0。我编写了以下代码: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/time.h> double getsecs(void) { st

我试图检测简单内存共享中的核心到核心延迟。我的目标是从两个不同的线程读取全局变量。假设变量开始时为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);
}
#包括
#包括
#包括
#包括
双getsecs(无效)
{
结构时间值电视;
gettimeofday(&tv,NULL);
返回tv.tv_sec+tv.tv_usec/1.0e6;
}
int x=0;
//计数=0;
void*changetoone(void*arg)
{
//sched_setaffinity(0);

对于(int i=0;i而言,
pthread\u join
的第一个参数是
pthread\u t
,而不是
pthread\u t*
。因此在调用它时不应该使用
&

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

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

您的代码行为未定义,您需要一些同步(至少是原子同步)。谢谢Barmar。我的问题有三个部分。(查看不同同步方法的核心到核心延迟如何变化-->a)简单共享b)使用原子指令c)使用互斥锁。因此,我们没有办法看到性能(线程执行的循环时间)没有任何同步?指向
pthread\u join
的参数应该是
thread1
,而不是
&thread1
。您应该得到一个关于不兼容类型的编译器警告。在C中,您受C内存模型的约束。您访问
x
竞争,编译器不需要每次通过循环重新加载它。(如果禁用所有优化,可能会看到不同的结果。)如果不同步,第二个线程可能会在第一个线程执行
printf()
之前将变量更改回0。您可能应该向printf添加一些内容,以便知道它是哪个线程,如
printf(“1%d\n”,x);
in
changetoone()
我修复了它,但代码仍然无法运行。如果我将printf放在while循环之外的线程中,我会得到这样的结果:0000000000000000000000000000000000000000000000000…111111111111111111111…0000000000000000000…1111111111…但我不确定这是否是我期望的输出。我最终想要得到时间这需要在两个不同内核中运行的两个线程中进行一次往返。当我运行它时,我得到了交替的
10101010…
。但是正如我们所说的,结果是未定义的,因为您没有同步。我不知道为什么它不为您运行,它为我运行。您对代码做了任何更改吗?另外,我正在中运行代码UbuntuVirtualBox只有一个内核。没有其他改动,但我在一个有4个内核的Mac上运行。这会影响时间,但不会改变程序是否运行。