线程无法识别标志的变化

Thread doesn't recognize change in a flag

我使用几个线程。所有 运行ning 只要 exit_flag 设置为 false。

我有特定线程无法识别标志中的更改,因此不会结束并释放其资源,我正在尝试了解原因。

更新: 在使用 gdb 调试了一下之后,我可以看到给定 'enough time' 有问题的线程确实检测到标志更改。 我由此得出的结论是,线程没有足够的时间来检测正常 运行.

中的变化

我如何 'delay' 我的主线程,足够长的时间让所有线程检测到标志变化,而不必加入它们? (使用 exit_flag 的目的是不加入线程,因为我不想为此管理所有线程 ID - 我只是分离它们中的每一个,除了处理输入的线程) . 我试过在 close_server() 方法中使用 sleep(5),在标志改变后,没有运气

备注:

  1. 相同标志上循环的其他线程确实成功终止

  2. exit_flag 声明为:static volatile bool exit_flag

  3. 所有线程都在读取标志,标志值仅在我有的close_server()方法中更改(仅这样做)

  4. 当一个线程在其改变之前读取标志时可能发生的数据竞争,对我来说无关紧要,只要在 while 循环的下一次迭代中它会读取正确的值.

  5. 线程本身没有发生错误(根据 strerr 和 stdout,它们是 'clean' 来自错误消息(对于我在线程中处理的错误)

  6. 即使在注释掉整个 while((!exit_flag) && (remain_data > 0)) 代码块时也会出现这种情况 - 所以这不是 sendfile 悬而未决的问题

station_info_t 结构:

typedef struct station_info {
    int socket_fd;
    int station_num;
} station_info_t;

有问题的线程代码:

void * station_handler(void * arg_p)
{
    status_type_t rs = SUCCESS;

    station_info_t * info = (station_info_t *)arg_p;
    int remain_data = 0;
    int sent_bytes = 0;
    int song_fd = 0;
    off_t offset = 0;
    FILE * fp = NULL;
    struct stat file_stat;

    /* validate station number for this handler */
    if(info->station_num < 0) {
        fprintf(stderr, "station_handler() station_num = %d, something's very wrong! exiting\n", info->station_num);
        exit(EXIT_FAILURE);
    }

    /* Open the file to send, and get his stats */
    fp = fopen(srv_params.songs_names[info->station_num], "r");

    if(NULL == fp) {
        close(info->socket_fd);
        free(info);
        error_and_exit("fopen() failed! errno = ", errno);
    }

    song_fd = fileno(fp);

    if( fstat(song_fd, &file_stat) ) {
        close(info->socket_fd);
        fclose(fp);
        free(info);
        error_and_exit("fstat() failed! errno = ", errno);
    }

    /** Run as long as no exit procedure was initiated */
    while( !exit_flag ) {
        offset = 0;
        remain_data = file_stat.st_size;

        while( (!exit_flag) && (remain_data > 0) ) {
            sent_bytes = sendfile(info->socket_fd, song_fd, &offset, SEND_BUF);
            if(sent_bytes < 0 ) {
                error_and_exit("sendfile() failed! errno = ", errno);
            }

            remain_data = remain_data - sent_bytes;
            usleep(USLEEP_TIME);
        }
    }

    printf("Station %d handle exited\n", info->station_num);

    /* Free \ close all resources */
    close(info->socket_fd);
    fclose(fp);
    free(info);
    return NULL;
}

我很乐意得到一些帮助。 谢谢大家

好吧,正如 user362924 所述,主要问题是我没有在主线程中加入线程,因此没有足够的时间退出。

如果出于某种原因不想加入所有线程并动态管理线程 ID,则该问题的解决方法是在主线程末尾使用 sleep 命令,用于一对夫妇秒。

当然,这种解决方法不是很好的做法,也不推荐(对于 google 之前到达这里的任何人)