pthreads: different behaviour on different thread count
So, I have a code (thread pool like) that creates few pthreads.
They are blocked on mutex first (while all threads not created) then wait on conditional variable until main thread broadcasts them a notification.I test this code on two PC: 1st - gentoo x64 with 2 core AMD, 2nd - mandriva x32 with p4 (HT on). And I got different results.
It works well on 1st PC with 2 threads in pool, and on 2nd with 3 threads in pool.
But! 1st PC with thread count more then 2: throws error EPERM from main thread while unlocking mutex (locked before). 2nd PC with thread count more then 3: throws error EINVAL from main thread while unlocking mutex (locked before) and from all sequential calls to mutex and cond from created threads.Any Idea? :)
p.s. threads mutex and cond created with NULL attrs
main():
...
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);
...
run():
while (running) {
lock();
Job* job = next();
if (job == NULL) {
wait();
unlock();
continue;
}
unlock();
job->execute();
delete job;
}
routine:
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(&q开发者_如何学编程ueue_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;
}
output on 2nd PC with 4 threads:
3076544208] hi! Im main thread! 3076544208] starting all threads 3076544208] locking... 3076544208] locked 3076544208] init: 3076544208] thread[1] = 3076541296 created 3076544208] thread[2] = 3068148592 created 3076544208] thread[3] = 3059755888 created 3076544208] thread[4] = 3051363184 created 3076544208] init done. 3076544208] unlocking... 3076544208] unlocked error=22 3051363184] run 3051363184] locking... 3051363184] locked error=22
I caught the bug! I forgot to initialize array threads
that is a field of my class. ephemient was right it's memory corruption.
精彩评论