[英]while loop reads same variable from 2 different pthreads but code not running
I am trying to detect core to core latency in simple memory sharing.我试图在简单的内存共享中检测核心到核心的延迟。 My objective is to read a global variable from two different threads.我的目标是从两个不同的线程读取全局变量。 Let's say the variable is x=0 at the beginning.假设变量一开始是 x=0。 Now one thread will read the value and change the x to 1. Another thread is reading the same variable and as soon as it reads x=1, it makes it 0. I have written the following code:现在一个线程将读取该值并将 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);
}
For some reason, the code is not running.出于某种原因,代码没有运行。 I am not familiar with using pthread and I think I made some silly mistakes.我不熟悉使用 pthread,我想我犯了一些愚蠢的错误。 Can anybody point out the mistake for me, please?有人能指出我的错误吗?
The first argument to pthread_join
is pthread_t
, not pthread_t*
. pthread_join
的第一个参数是pthread_t
,而不是pthread_t*
。 So you shouldn't use &
when calling it.所以你不应该在调用它时使用&
。
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
The actual behavior of the program is undefined because of lack of synchronization between the threads when accessing x
.由于访问x
时线程之间缺乏同步,程序的实际行为是不确定的。 But this will at least allow the threads to run.但这至少将允许线程运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.