lldb暂停线程,而其他线程继续

时间:2019-05-16 15:08:12

标签: xcode multithreading debugging lldb

使用lldb作为调试器,您可以暂停一个线程,而其他线程继续吗?

下面是C的简单pthreads多线程示例。

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>

/*********************************************************************************
 Start two background threads.
 Both print a message to logs.
 Goal: pause a single thread why the other thread continues
 *********************************************************************************/

typedef struct{
    int count;
    char *message;
}Chomper;

void *hello_world(void *voidptr) {
    uint64_t tid;
    unsigned int microseconds = 10;
    assert(pthread_threadid_np(NULL, &tid)== 0);
    printf("Thread ID: dec:%llu hex: %#08x\n", tid, (unsigned int) tid);
    Chomper *chomper = (Chomper *)voidptr;  // help the compiler map the void pointer to the actual data structure

    for (int i = 0; i < chomper->count; i++) {
        usleep(microseconds);
        printf("%s: %d\n", chomper->message, i);
    }
    return NULL;
}

int main() {

        pthread_t myThread1 = NULL, myThread2 = NULL;

        Chomper *shark = malloc(sizeof(*shark));
        shark->count = 5;
        shark->message = "hello";

        Chomper *jellyfish = malloc(sizeof(*jellyfish));
        jellyfish->count = 20;
        jellyfish->message = "goodbye";

        assert(pthread_create(&myThread1, NULL, hello_world, (void *) shark) == 0);
        assert(pthread_create(&myThread2, NULL, hello_world, (void *) jellyfish) == 0);
        assert(pthread_join(myThread1, NULL) == 0);
        assert(pthread_join(myThread2, NULL) == 0);

        free(shark);
        free(jellyfish);
        return 0;
}

1 个答案:

答案 0 :(得分:2)

取决于您的要求。当其他线程正在运行时,您无法暂停并检查一个线程的状态。进程运行后,您必须暂停它以读取内存,变量等。

但是您可以恢复该过程,但只允许运行一些线程。一种方法是使用:

(lldb) thread continue <LIST OF THREADS TO CONTINUE>

另一种方法是使用Python中的lldb.SBThread.Suspend() API来阻止某些线程或多个线程运行,直到您使用lldb.SBThread.Resume()恢复它们为止。我们之所以没有为此提供命令行命令,是因为我们认为这样做很容易使您陷入僵局,因此我们强迫您通过SB API来表明您知道自己在做什么...但是如果您由于需要经常执行此操作,因此很容易制作一个基于Python的命令来执行此操作。参见:

https://lldb.llvm.org/use/python-reference.html#create-a-new-lldb-command-using-a-python-function

了解详情。