如何使用本杀死线程数组? [英] How to use this for killing array of threads?

查看:107
本文介绍了如何使用本杀死线程数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code工作得很好,但如何用它来杀死剩余线程的阵列?

This code worked fine , but how to use it to kill for array of remaining threads?

#include<stdio.h>
#include<signal.h>
#include<pthread.h>

void *print1(void *tid) 
{
    pthread_t *td= tid;
    pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_lock(&lock1);
    printf("1");
    printf("2");
    printf("3");
    printf("4\n");
    printf("Coming out of thread1 \n");
    sleep(2);
    pthread_mutex_unlock(&lock1);
    pthread_kill(*td,SIGKILL);//killing remaining all threads 
    return NULL;
}
void *print2(void *arg) 
{
    pthread_mutex_t *lock = arg;
    pthread_mutex_lock(lock);
    sleep(5);        
    printf("5");
    sleep(5);
    printf("6");
    sleep(5);
    printf("7");
    sleep(5);
    printf("8\n");
    fflush(stdout);
    pthread_mutex_unlock(lock);
    return NULL;
}
int main() 
{
    int s;
    pthread_t tid1, tid2;
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    printf("creating Thread 1and 2 \n");
    sleep(2);
    pthread_create(&tid1, NULL, print1,&tid2);
    pthread_create(&tid2, NULL, print2,&lock);
    printf("Running Thread 1\n");
    sleep(2);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    return 0;
}

注释:请删除并添加有关code一些额外的信息。编辑是不是让我来编辑code。

Comments: Please delete this and add some extra information about the code. The editor is not allowing me to edit the code.

推荐答案

。有没有一个正确的方式来做到这一点。

However you want. There is no "one right way" to do this.

也许最简单的方法是通过调用一个使用功能那么pthread_cond_timedwait 和更换您的通话睡眠 predicate导致线程调用了pthread_exit

Probably the easiest way is to replace your calls to sleep with calls to a function that uses pthread_cond_timedwait and a predicate that causes the thread to call pthread_exit.

在psuedo- code,替换为睡眠这个逻辑调用:

In psuedo-code, replace calls to sleep with this logic:


  1. 计算休眠状态,直到时间。

  1. Compute the time to sleep until.

锁定互斥。

检查predicate设置退出,如果是的话,叫了pthread_exit

Check if the predicate is set to exit, if so, call pthread_exit.

呼叫那么pthread_cond_timedwait

检查predicate设置退出,如果是的话,叫了pthread_exit

Check if the predicate is set to exit, if so, call pthread_exit.

检查过期时间,如果没有,请停止4。

Check if the time expired, if not, go to stop 4.

和终止线程,这样做:


  1. 锁定互斥。

  1. Lock the mutex.

设置predicate退出。

Set the predicate to exit.

呼叫调用pthread_cond_broadcast

释放互斥锁。

呼叫在pthread_join 的线程等待,直到他们已经终止。

Call pthread_join on the threads to wait until they've terminated.

这篇关于如何使用本杀死线程数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆