gpt4 book ai didi

linux - pthreads:不同线程数的不同行为

转载 作者:太空狗 更新时间:2023-10-29 12:38:03 24 4
gpt4 key购买 nike

所以,我有一个代码(类似线程池)创建了几个 pthreads。
它们首先被互斥锁阻塞(所有线程都未创建),然后等待条件变量,直到主线程向它们广播通知。

我在两台 PC 上测试此代码:1st - gentoo x64,2 核 AMD,2nd - mandriva x32,p4(HT 开启)。我得到了不同的结果。

它在池中有 2 个线程的1st PC 和池中有 3 个线程的2 PC 上运行良好。
但是!
1st 线程数超过 2 的 PC:在解锁互斥量(之前已锁定)时从主线程抛出错误 EPERM。第 2 线程数超过 3 的 PC:在解锁互斥量(之前已锁定)时以及从创建的线程对互斥量和条件的所有顺序调用时从主线程抛出错误 EINVAL。

有什么想法吗? :)

附注使用 NULL attrs 创建的线程 mutex 和 cond

主要():

...
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&queue_condition, NULL);
running = true;

lock();
while(pool_size<limit) {
pthread_create(&threads[pool_size++], NULL, &run, this)
}
unlock();

sleep(2);
schedule(new SimpleJob(...));
sleep(2);
...

运行():

while (running) {
lock();
Job* job = next();

if (job == NULL) {
wait();
unlock();
continue;
}
unlock();
job->execute();
delete job;
}

常规:


void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
void wait() {
pthread_cond_wait(&queue_condition, &mutex);
}
void notifyAll() {
pthread_cond_broadcast(&queue_condition);
}
void schedule(Job* job) {
lock();
job_queue.push(job);
notifyAll();
unlock();
}
Job* next() {
if (job_queue.empty()) {
return NULL;
}
Job* job = job_queue.front();
job_queue.pop();
return job;
}
在具有 4 个线程的第二台 PC 上输出:

3076544208] hi! Im main thread!3076544208] starting all threads3076544208] locking...3076544208] locked3076544208] init:3076544208] thread[1] = 3076541296 created3076544208] thread[2] = 3068148592 created3076544208] thread[3] = 3059755888 created3076544208] thread[4] = 3051363184 created3076544208] init done.3076544208] unlocking...3076544208] unlocked error=223051363184] run3051363184] locking...3051363184] locked error=22

最佳答案

我发现了错误!我忘记初始化数组 threads 这是我类(class)的一个字段。 ephemient 是对的,它是内存损坏。

关于linux - pthreads:不同线程数的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5008405/

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