我使用几个线程。只要 exit_flag 设置为 false,所有操作都会运行。
我有特定的线程无法识别标志中的更改,因此没有结束并释放其资源,我正在尝试理解原因。
更新:使用 gdb 进行一些调试后,我可以看到在给定“足够的时间”的情况下,有问题的线程确实检测到了标志更改。 我由此得出的结论是,线程没有足够的时间来检测正常运行中的变化。
我如何“延迟”我的主线程,足够长的时间让所有线程检测到标志更改,而不必加入它们? (使用exit_flag
的目的是不加入线程,因为我不想为此管理所有线程ID - 我只是分离它们中的每一个,除了处理输入的线程)。
我尝试过使用 sleep(5)
在close_server()
方法,改变标志后,没有运气
注释:
在相同标志上循环的其他线程确实成功终止
exit_flag 声明为:
static volatile bool exit_flag
所有线程都读取标志,标志值仅在
close_server()
中更改我有的方法(仅此目的)当线程在更改之前读取标志时可能会发生数据竞争,这对我来说并不重要,只要在 while 循环的下一次迭代中它将读取正确的值即可。
线程本身没有发生错误(根据 strerr 和 stdout,它们从错误消息中“干净”(对于我在线程中处理的错误)
即使注释掉整个
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
命令,以实现几秒钟。
当然,这种解决方法不是一个好的做法,也不推荐(对于通过谷歌到达这里的任何人)
关于c - 线程无法识别标志中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35638991/