gpt4 book ai didi

c++ - pthread_cancel 中的非法查找

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:52 26 4
gpt4 key购买 nike

我有一个程序试图通过已实现的池使用创建和取消。

创建如下:

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 索引中的线程?

而且我找不到任何关于 Illegal Seek 的信息..

谢谢大家的帮助

谢谢

最佳答案

问题是 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 数组中,即使它实际上还不是一个线程。在调用 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++ - pthread_cancel 中的非法查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13477150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com