非法寻求pthread_cancel
Illegal Seek in pthread_cancel
我有一个程序,它试图通过一个实现的池来使用创建和取消。
创建如下:
int threadsNum=10;
while (created<threadsNum){
pthread_t newThread;
pthread_struct *st; //Open the thread that handle the deleting of the sessions timeout.
st = (pthread_struct*)malloc(sizeof(pthread_struct));
st->id = created;
st->t = newThread;
pthread_mutex_lock( &mutex_threadsPool );
readingThreadsPool[created] = st;
pthread_mutex_unlock( &mutex_threadsPool );
if((threadRes1 = pthread_create( &newThread, NULL, pcapReadingThread, (void*)created)))
{
syslog(LOG_CRIT, "Creating Pcap-Reading Thread %d failed.",created);
printf( "Creating Pcap-Reading Thread %d failed.n",created);
exit(1);
}
syslog(LOG_INFO, "Created Pcap-Reading Thread %d Successfully.",created);
created++;
}
稍后我尝试取消它们并重新启动它们:
pthread_t t;
pthread_struct* tstr;
int i;
pthread_mutex_unlock( &mutex_threadsPool );
//first go on array and kill all threads
for(i = 0; i<threadsNum ; i++ ){
tstr = readingThreadsPool[i];
if (tstr!=NULL){
t = tstr->t;
if (pthread_cancel(t)!=0){
perror("ERROR : Could not kill thread");
}
else{
printf("Killed Thread %d n",i);
}
}
}
到目前为止一切顺利,但唯一的问题是输出是错误:无法杀死线程:非法搜索被杀死的线程 1
被杀的线程 2
被杀的线程3
被杀的线程 4
被杀的线程 5
被杀的线程 6
被杀死的线程 7
被杀死的线程 8
被杀的线程 9
为什么它不也杀死 0 索引中的线程?
而且我找不到任何关于非法寻求的信息。
感谢您的帮助
谢谢
问题是newThread
在初始化之前就被使用了:
pthread_t newThread;
pthread_struct *st;
st = (pthread_struct*)malloc(sizeof(pthread_struct));
st->id = created;
st->t = newThread;
但newThread
直到成功调用 pthread_create()
后才会收到值。似乎newThread
变量在循环的后续迭代中保留其先前的值,这导致正确取消除最后一个启动的线程之外的所有线程,因为它的 id 永远不会插入到 readingThreadsPool
数组中。
您需要在调用 pthread_create()
后填充st->t
成员。
按照当前的代码,可以将条目插入到 readingThreadsPool
数组中,即使它实际上还不是线程。将插入逻辑放在调用 to pthread_create()
之后:
if((threadRes1 =
pthread_create(&(st->t), NULL, pcapReadingThread, (void*)created)))
{
syslog(LOG_CRIT, "Creating Pcap-Reading Thread %d failed.",created);
printf( "Creating Pcap-Reading Thread %d failed.n",created);
exit(1);
}
pthread_mutex_lock( &mutex_threadsPool );
readingThreadsPool[created] = st;
pthread_mutex_unlock( &mutex_threadsPool );
或者,如果 pcapReadingThread()
函数访问 readingThreadsPool
并期望自己有一个条目(我认为可能是由于传递created
而出现这种情况),则将pthread_create()
包含在mutex_threadsPool
锁中。
相关文章:
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 直接读取 pthread 互斥锁的所有者字段是否安全?
- 为什么 pthread 会减慢代码速度?
- 对 pthread CLion 的未定义引用
- C++ 17:pthread的生成文件标志
- 将带有结构的参数传递给 pthread
- Posix 线程类和启动例程 (pthread)
- 在 pthread 中使用共享变量