相关疑难解决方法(0)

使用pthread互斥锁保护变量是否保证它也不会被缓存?

考虑一个简单的(在我的情况下是全局)变量:

int i;
Run Code Online (Sandbox Code Playgroud)

在某处访问此变量

pthread_mutex_lock(i_mutex);
if(i == other value) {
  do_something();
}
pthread_mutex_unlock(i_mutex);
Run Code Online (Sandbox Code Playgroud)

另一个线程i 在保持时更新i_mutex.编译器可以缓存值,i所以我没有得到最近的值?一定i是不稳定的?

c pthreads

33
推荐指数
2
解决办法
6718
查看次数

函数调用是一个内存障碍吗?

考虑这个C代码:

extern volatile int hardware_reg;

void f(const void *src, size_t len)
{
    void *dst = <something>;

    hardware_reg = 1;    
    memcpy(dst, src, len);    
    hardware_reg = 0;
}
Run Code Online (Sandbox Code Playgroud)

memcpy()呼叫必须在两个任务之间发生.通常,由于编译器可能不知道被调用函数将执行什么操作,因此它无法将对函数的调用重新排序为在赋值之前或之后.但是,在这种情况下,编译器知道函数将执行什么操作(甚至可以插入内联内置替换),并且它可以推断出memcpy()永远不能访问的内容hardware_reg.在我看来,编译器在移动memcpy()调用时会遇到麻烦,如果它想这样做的话.

所以,问题是:单独的函数调用是否足以发出阻止重新排序的内存屏障,或者在这种情况下,在调用之前和之后需要显式内存屏障memcpy()

如果我误解了事情,请纠正我.

c

20
推荐指数
1
解决办法
4954
查看次数

pThread同步问题有问题

我正面临着pthread的同步问题.threadWaitFunction1,是一个线程等待函数.我希望行没有.247 flag = 1只有在243-246完成后才能执行.但我觉得很奇怪,有时候,它会在243-246结束前直接跳到247.

请帮我.

提前致谢.

236   struct timespec timeToWait;
237   static void* threadWaitFunction1(void *timeToWaitPtr)
238   {
239       cout << "Setting flag =0 inside threadWaitFunction1\n";
240       
241       cout << "Inside threadWaitFunction\n";
242       struct timespec *ptr = (struct timespec*) timeToWaitPtr;
243       pthread_mutex_lock(&timerMutex);
          flag = 0;
244       pthread_cond_timedwait(&timerCond, &timerMutex, ptr);
          flag=1;
245       pthread_mutex_unlock(&timerMutex);
246       cout << "Setting flag =1 inside threadWaitFunction1\n";
247       
248
249    }
Run Code Online (Sandbox Code Playgroud)

创建并调用上述线程的线程是:

263  static void timer_trackStartTime ()
264  {
265       struct timeval now;
266       pthread_t thread;
267 …
Run Code Online (Sandbox Code Playgroud)

c linux pthreads

3
推荐指数
1
解决办法
1065
查看次数

标签 统计

c ×3

pthreads ×2

linux ×1