【发布时间】:2013-10-18 01:39:03
【问题描述】:
我正试图以这种方式取消一个线程:
pthread_cancel(threads[id]);
我在取消线程之前释放互斥锁。
然后我需要重新启动它,因为它会导致死锁
usleep(1);
pthread_create(&threads[id], NULL, aFunction, &id );
usleep(1);
pthread_join(threads[id], NULL);
usleep(1);
我尝试删除 pthread_join,但没有成功。
这是代码的很大一部分:
#define LEFT(i) i
#define RIGHT(i) (i+1) % N
#define CreateSemaphore(s,v) sem_init( &s, 0, v)
#define WaitSemaphore(s) sem_wait( &s )
#define SignalSemaphore(s) sem_post( &s )
#define ReleaseSemaphore(s) sem_destroy( &s )
void restart(int id) {
release(id, LEFT(id));
int res;
if (allocated[id][RIGHT(id)] == 1) {
release(id, RIGHT(id));
}
res = pthread_cancel(threads[id]);
if (res != 0) {
perror("Thread cancelation failed");
exit(EXIT_FAILURE);
}
usleep(1);
res = pthread_create(&threads[id], NULL, aFunction, &id );
usleep(1);
if (res != 0 ) {
fprintf( stderr, "Error creating the thread %d \n", id );
exit( 1 );
}
printf("Waiting for thread to finish...\n");
res = pthread_join(threads[id], NULL);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
} else
printf("Passed join...\n");
usleep(1);
}
void * aFunction( void *i )
{
int value = *((int *)i);
while ( 1 ){
think( value );
take( value );
eat( value );
drop( value );
}
pthread_exit( NULL );
}
void take( int i ) {
request(i, LEFT(i));
WaitSemaphore( fork[LEFT(i)] );
allocation(i, LEFT(i));
usleep(100);
request(i, RIGHT(i));
WaitSemaphore( fork[RIGHT(i)] );
allocation(i, RIGHT(i));
usleep(100);
}
void drop( int i )
{
SignalSemaphore( forks[LEFT(i)] );
release(i, LEFT(i));
usleep(100);
SignalSemaphore( forks[RIGHT(i)] );
release(i, RIGHT(i));
usleep(100);
}
void release(int id, int f) {
WaitSemaphore(mutex[f]);
beingUsed[id][f] = 0;
currentAvail[f] = 1;
SignalSemaphore(mutex[f]);
}
【问题讨论】:
-
如果一个线程导致死锁,这意味着它正在使用某种具有互斥锁(或类似)的资源。销毁线程是不够的,还需要释放资源。
-
完整显示您的代码,
dead lock取决于您的aFunction或其他线程。没有代码,就没有真相。 -
好吧,我必须造成死锁并修复它。我确实在取消线程之前释放了互斥锁。
-
@CharlesWelton:至少在 POSIX 下,
sem_wait()被定义为取消点:pubs.opengroup.org/onlinepubs/9699919799/functions/…(向下滚动到取消点) . -
当您将 gdb 附加到您的死锁进程并检查线程及其调用堆栈时,它在哪里被阻塞了?
标签: c multithreading unix pthreads semaphore