【发布时间】: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,而不是&thread1。您应该已经收到有关不兼容类型的编译器警告。 -
在 C 中,您受 C 内存模型的约束。您访问
x比赛,编译器不需要每次通过循环重新加载它。 (也许如果你禁用所有优化,你会看到不同的东西。) -
如果没有同步,第二个线程可能会在第一个线程执行其
printf()之前将变量更改回 0。您可能应该在 printf 中添加一些内容,以便知道它是哪个线程,例如changetoone()中的printf("1 %d\n", x);
标签: c linux while-loop pthreads