c如何通过更改信号量的值来启动停止的线程

时间:2017-07-20 11:39:59

标签: c multithreading semaphore

我试图了解线程和信号量。我希望能够启动和停止一个线程。我在下面有一些代码创建了一个线程然后因为semaphore的值为0而停止,因此sem_wait()将不会返回。如何更改semaphoremain()的值以便我可以启动该帖子?例如,如果我输入带getchar()的字符,那么启动线程?我尝试使用sem_post()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

sem_t semaphore;

void threadfunc() {
    printf("thread started\r\n");
    while (1) {
        sem_wait(&semaphore);
        printf("Hello from da thread!\n");
        sem_post(&semaphore);
        sleep(1);
    }
}

int main(void) {

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

    pthread_t *mythread;

    mythread = (pthread_t *)malloc(sizeof(*mythread));

    // start the thread
    printf("Starting thread, semaphore is locked.\n");
    pthread_create(mythread, NULL, (void*)threadfunc, NULL);


    sem_wait(&semaphore);

    getchar();
    //Now start the thread

    return 0;
}

1 个答案:

答案 0 :(得分:2)

我在此处看到的问题是main()永远不会进入getChar()来电,因为您在其中调用了sem_wait()

请改为尝试:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

sem_t semaphore;

void* threadfunc(void*) {
    printf("thread started\r\n");
    while (1) {
        // Wait for main to post to the semaphore
        sem_wait(&semaphore); 

        printf("Hello from da thread!\n");

        // Post to the semaphore ourselves since main will only do one
        sem_post(&semaphore);
        sleep(1);
    }
}

int main(void) {
    pthread_t mythread;
    sem_init(&semaphore, 0, 0);

    // start the thread
    printf("Starting thread, semaphore is locked.\n");
    pthread_create(&mythread, NULL, threadfunc, NULL);

    getchar();
    sem_post(&semaphore);

    // Wait for threadfunc to return, otherwise our program dies early.
    pthread_join(&mythread, NULL);
    return 0;
}

在此,threadfunc()等待初始值为0的信号量。 main()会立即进入getchar()来电,之后会发布信号量,允许threadfunc()继续。

此处的另一个关键是在pthread_join()结束时对main()的调用。这会导致main()在继续之前等待threadfunc()返回。一旦main()返回,您的程序将被操作系统拆除,无论您的线程是否已完成。

在这种情况下,threadfunc()将永久运行,main()永远不会返回。

另请注意threadfunc()的更改返回类型。 pthreads需要一个获取并返回void*参数的函数。你的演员只是隐藏你的功能没有正确的签名。 (谢谢@mch)