我使用几个线程。 只要exit_flag设置为 false,所有线程都会运行。
我有特定的线程无法识别标志的变化,因此不会结束并释放其资源,我试图了解原因。
更新:在使用 gdb 进行一些调试后,我可以看到给定"足够的时间",有问题的线程确实检测到标志更改。我由此得出的结论是,线程没有足够的时间来检测正常运行的变化。
我怎样才能"延迟"我的主线程,足够长的时间让所有线程检测到标志更改,而不必加入它们?(使用 exit_flag
是为了不加入线程,因为我不想为此管理所有线程 ID - 我只是分离它们中的每一个,除了处理输入的线程)。我尝试在close_server()
方法中使用sleep(5)
,在标志更改后,没有运气
笔记:
在同一标志上循环的其他线程确实成功终止
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! exitingn", 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 exitedn", info->station_num);
/* Free close all resources */
close(info->socket_fd);
fclose(fp);
free(info);
return NULL;
}
我很乐意得到一些帮助。谢谢大家
好吧,正如user362924所述,主要问题是我没有加入主线程中的线程,因此不允许它们有足够的时间退出。
如果由于某种原因不想加入所有线程并动态管理线程 id,则解决此问题的方法是在主线程末尾使用 sleep
命令几秒钟。
当然,这种解决方法不是好的做法,不建议(对于通过Google到达此处的任何人)