0

我正在尝试以这种方式取消线程:

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]);

}
4

1 回答 1

0

您是否尝试在线程代码中使用 pthread_exit(1) ?这是在完成工作时完成正在运行的线程的另一种方法。

于 2013-11-26T14:23:30.563 回答