【发布时间】:2011-10-07 00:11:42
【问题描述】:
我想通过控制哪些线程何时执行来调试多线程程序。我正在使用 C++ 和 gdb。除了主线程(用于示例程序)之外,我还有两个线程,我想调试一个线程,同时保持另一个线程停止。
这是我写的示例程序:
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#define NUM_THREADS 2
using namespace std;
void * run (void *) {
for (int i = 0; i < 3; ++i) {
sleep(1);
cout << i << " " << pthread_self() << endl;
}
pthread_exit(NULL);
}
int main (int argc, char** argv) {
cout << "Start..." << endl;
int rc;
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
rc = pthread_create(&threads[i], NULL, run, NULL);
if (rc) {
cout << "pthread_create returned error: " << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
我运行 gdb 并在sleep(1) 处设置断点。然后我运行程序。我得到三个线程(线程 2 和 3 是 pthreads),程序位于线程 2(在sleep(1) 等待)。现在,我想将线程 3 保留在任何位置,并继续单步执行线程 2(通过在 gdb 中执行 c)。
我尝试过的是set scheduler-locking on,但它似乎没有像我预期的那样工作。我在线程 2,我 set scheduler-locking on,continue 几次(到目前为止一切顺利,我仍在线程 2),切换到线程 3,set scheduler-locking on,continue,由于某种原因,我我回到线程 2 ......当我不应该的时候(根据我的理解)。有什么我想念的吗?
【问题讨论】: