C 中取消线程

标签 c multithreading unix pthreads semaphore

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

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

}

最佳答案

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

关于C 中取消线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440182/

相关文章:

java - 当某些事务的顺序很重要时,我如何多线程处理队列消费者?

c - 如何创建 2 个线程并交替打印线程 ID 和从 1 到 20 的数字?

c - 输出的奇怪行为

c - Char变量如何在C中工作

c - 有些值打印了我不想要的 i (i = 0; i < 10; i++) 的额外次数。在C中使用for循环时

这个阿克曼函数的实现可以称为尾递归吗?

c - 向所有线程发送信号

shell - shell 的 `source` 是 POSIX 标准的吗?

linux - 如何使用 hexdump 显示前 x 个字节?

linux - 如何在 Linux 中将天数转换为秒数