首页 > 解决方案 > 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;
}

标签: xcodemultithreadingdebugginglldb

解决方案


取决于你在问什么。当其他线程正在运行时,您不能暂停并检查一个线程的状态。一旦进程运行,您必须暂停它以读取内存、变量等。

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

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

另一种方法是使用lldb.SBThread.Suspend()Python 中的 API 来阻止一些线程或多个线程运行,直到您使用lldb.SBThread.Resume(). 我们没有为此创建命令行命令,因为我们认为这样做太容易让自己陷入僵局,因此我们强迫您通过 SB API 来显示您知道自己在做什么...但是如果您需要经常这样做,很容易制作一个基于 Python 的命令来完成它。看:

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

详情。


推荐阅读