【发布时间】:2011-04-28 11:57:52
【问题描述】:
我正面临与 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 }
创建和调用上述线程的线程是:
263 static void timer_trackStartTime ()
264 {
265 struct timeval now;
266 pthread_t thread;
267
268 printf("Inside trackStartTime: flag = %d\n",flag);
269
270 /* Setting timer expiration */
271 timeToWait.tv_sec = lt_leak_start_sec;; // First expiry after 1 sec
272 timeToWait.tv_nsec = lt_leak_start_nsec;
273 pthread_create(&thread, NULL, threadWaitFunction1, &timeToWait);
274 pthread_join(thread, NULL);
275 //pthread_kill(thread, SIGKILL); // Destroying the thread to ensure no leaks
276
.
.
283 }
如果我使用 pthread_mutex_lock 保护整个函数,但同样的问题仍然存在。如何保证有序执行?谁能帮忙?
编辑:now.tv_sec 和 now.tv_nsec 从代码中删除。 *编辑:更改了互斥锁内的标志(仍然不起作用)*
【问题讨论】:
-
这个问题在目前的形式下是无法回答的,因为您没有说明您是如何衡量
flag何时/何地发生变化的。请注意,在您不持有互斥锁的情况下更改flag几乎肯定是虚假的,除非这是唯一可以访问flag的线程,在这种情况下,您的问题毫无意义。 -
@R:标志改变,只有当开始时间:当前时间+lt_leak_start_sec。我认为您错过了传递给线程函数的参数。
-
@R: 条件互斥锁被保持,直到达到结构中指定的时间。
-
确保 (now.tv_usec * 1000) + lt_leak_start_nsec;不会溢出。您只能将 tv_nsec 设置为最大值 999999999,如果表达式大于此值,则应从 tv_nsec 中减去 999999999,并将 tv_sec 加 1。如果您的
timeToWaitPtr包含无效的 tv_nsec(大于 999999999),pthread_cond_timedwait 将失败(您也应该检查它的返回值。) -
@ninjalj:是的。 XBD 4.11 (pubs.opengroup.org/onlinepubs/9699919799/basedefs/…) 读取:“以下函数相对于其他线程同步内存”后跟一个包含
pthread_mutex_lock和pthread_mutex_unlock的列表。