c pthreads从主线程中无限循环中止轮询

时间:2015-02-23 18:46:56

标签: c multithreading pthreads pipe polling

在一个线程中我使用poll来阻塞线程,直到有东西要读,但我需要关闭线程并在我的程序捕获信号时进行清理。

我尝试使用管道并将管道的读取末尾添加到poll使用的文件描述符集。然后,当我决定中止轮询并退出线程时,我只是将一些数据写入管道的写入端。

看起来非常直接,但显然它并不像我想象的那么简单。以下是它背后的一般逻辑:

int pipefd[2];

int main(){ 
    // create thread and init mutex etc...
    pipe(pipefd); // init pipe

    BLOCK_UNTIL_SIGINT(); // block until a SIGINT signal is received

    pthread_mutex_unlock(&mx); // unlock mutex

    write(pipefd[1], NULL, 8); // write some data to the write end of the pipe
    close(pipefd[1]);
    // cleanup
}

/* Returns 1 (true) if the mutex is unlocked, which is the
 * thread's signal to terminate. 
 */
int needQuit(pthread_mutex_t *mtx) {
  switch(pthread_mutex_trylock(mtx)) {
    case 0: /* if we got the lock, unlock and return 1 (true) */
      pthread_mutex_unlock(mtx);
      return 1;
    case EBUSY: /* return 0 (false) if the mutex was locked */
      return 0;
  }
  return 1;
}


void *thread_func(void *param){
    struct pollfd p[2];
    pthread_mutex_t *mx = (pthread_mutex_t*) param;

    bzero(&p, sizeof(p));

    p[0].fd = fd; // file descriptor to file I wish to read from when there's data to read
    p[0].revents = 0;
    p[0].events = POLLIN|POLLPRI;

    p[1] = p[0];
    p[1].fd = pipefd[0];

    while (!needQuit(mx)) { // repeat until mutex is unlocked
        if (poll(p, 1, -1)) { // block until there is something to read from the pipe or file
            // do something
        }
    }
    // cleanup
}

我认为当我在管道的写端写一些数据时,民意调查会返回,但绝对没有任何反应......

0 个答案:

没有答案