【问题标题】:while loop reads same variable from 2 different pthreads but code not runningwhile 循环从 2 个不同的 pthread 读取相同的变量,但代码未运行
【发布时间】:2020-06-06 19:55:12
【问题描述】:

我正在尝试检测简单内存共享中的核心到核心延迟。我的目标是从两个不同的线程中读取一个全局变量。假设变量一开始是 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,我认为我犯了一些愚蠢的错误。谁能帮我指出错误,好吗?

【问题讨论】:

  • 您的代码有未定义的行为,您需要一些同步(至少是原子的)。
  • 谢谢巴尔玛。我的问题有 3 个部分。 (查看不同同步方法的核心到核心延迟如何变化--> a)简单共享 b)使用原子指令 c)使用互斥锁。那么有没有什么方法可以在没有任何同步的情况下查看性能(线程执行的循环时间)?
  • pthread_join 的参数应该是 thread1,而不是 &amp;thread1。您应该已经收到有关不兼容类型的编译器警告。
  • 在 C 中,您受 C 内存模型的约束。您访问x 比赛,编译器不需要每次通过循环重新加载它。 (也许如果你禁用所有优化,你会看到不同的东西。)
  • 如果没有同步,第二个线程可能会在第一个线程执行其printf() 之前将变量更改回 0。您可能应该在 printf 中添加一些内容,以便知道它是哪个线程,例如 changetoone() 中的 printf("1 %d\n", x);

标签: c linux while-loop pthreads


【解决方案1】:

pthread_join 的第一个参数是pthread_t,而不是pthread_t*。所以调用时不要使用&amp;

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

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

【讨论】:

  • 我修复了它,但代码仍然无法运行。如果我将 printf 放在 while 循环之外的线程中,我会得到如下信息:000000000000000000000000000000000000000000000...111111111111111111111111111....0000000000000....1111期待。我最终希望获得在 2 个不同内核中运行的 2 个线程中往返所需的时间。
  • 当我运行它时,我得到了交替的10101010...。但正如我们所说,结果是不确定的,因为您没有同步。
  • 我不知道为什么它不适合你,它适合我。
  • 您是否对代码进行了任何更改?另外,我在只有一个内核的 Ubuntu virtualbox 中运行代码。
  • 没有其他改动,但我在 4 核的 Mac 上运行。这会影响时间,但不应该改变程序是否运行。
猜你喜欢
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 2013-02-06
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多