使用信号量时可以从c中的线程返回一个值吗

标签 c pthreads semaphore

我有一个 C 程序,它在启动时创建一个线程。该线程的目的是根据指示将固件刷新到设备。因此,当线程启动时,它会等待信号量,并且主应用程序将sem_post(&semaphore);发布到线程中的信号量,并且线程将完成其任务。

有时此任务可能会失败(如果存在硬件问题)。我的问题是我可以将线程中的值返回到主应用程序中信号量发布到的位置吗?固件的刷新是通过system()完成的,结果返回到int变量res。我想将此值返回到主应用程序?

这是主题:

static void *flash_firmware(void *param) {

    int res;
    char thread_Buf[SM_BUF];

    printf("Started thread\r\n");

    while(running == 1) {

        sem_wait(&semaphore);

        if(running == 1) {
            printf("*************Flashing firmware*************\r\n");
            snprintf(thread_Buf, SM_BUF, prog_path_printf,
                    programmingPtr->binary_filename, programmingPtr->debugger_serialnumber);

            res = system(thread_Buf); //flash firmware

        }
        else
            printf("Exiting thread \r\n");

    }

    return NULL;

}

这是我创建线程的 main() 代码片段。

#define THREADS 2
pthread_t thread_ID [THREADS];

int volatile running = 1;
sem_t semaphore;


int main(int argc, char *argv[])
{

/initialize semaphores to be used with threads in this process, set value to 0 initially
    sem_init(&semaphore, 0, 0);


    //create threads for DUTs 1 & 3
    pthread_create(&thread_ID[0], NULL, flash_firmware, &programmingPtr);

}

然后在另一个源文件中,sem_post(&semaphore); 将被执行,线程将继续进行。

最佳答案

是的,你可以。

您可以使用 pthread_exit() 返回指向所需返回值的指针,然后用 calling pthread_join() 捕获它.

只需确保指针引用的是静态或已分配的内存位置。

如果它对您来说有足够的信息,您也可以将指针用作整数,例如:

pthread_exit((void *)0);

int ret;
pthread_join(tid , (void **)&ret);

关于使用信号量时可以从c中的线程返回一个值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46686185/

相关文章:

c - 向等待锁的线程发出信号,表明该锁已变得无关紧要

PHP sem_get() 不起作用

c++ - Linux下调用semget()时EINVAL

c - printf 和 vprintf 函数系列之间有什么区别,我什么时候应该使用一个而不是另一个?

c++ - 分配两个数组一次调用 cudaMalloc

使用 cJSON.h 创建 json 对象

c - 在 C 的不同线程中运行函数内的一组特定行

c++ - 联盟内部结构

c - 将 "thread number"传递给 pthread_create

c - 在c中使用POSIX Semaphore进行多线程