如何从一组线程中杀死一个特定的线程

时间:2021-07-30 20:40:34

I am creating an array of threads based on the number of records in a database. Each thread then polls an ipaddress and then sleeps for a time and then repolls again. I periodically check the database for any change in the number of hosts. If there are more hosts I start another thread. If there are less hosts I need to kill the specific thread that was monitoring that host. How do i kill the specific thread.

我正在根据数据库中的记录数创建一个线程数组。然后每个线程轮询一个ipaddress,然后休眠一段时间,然后再次重新加载。我会定期检查数据库中主机数量的任何变化。如果有更多的主机我开始另一个线程。如果主机较少,我需要杀死监视该主机的特定线程。我如何杀死特定的线程。

enter code here protected static void GetThreads()
    {
        Thread[] threads;
        do
        {
            dt = getIP_Poll_status();
            threads = new Thread[dt.Rows.Count];
            Console.WriteLine(dt.Rows.Count + " Threads");
            for (int i = 0; i < threads.Length; ++i)
            {
                string ip = dt.Rows[i][0].ToString();
                int sleep = Convert.ToInt32(dt.Rows[i][1].ToString());
                string status = dt.Rows[i][2].ToString();
                string host = dt.Rows[i][3].ToString();
                Hosts.Add(host);
                string port = dt.Rows[i][4].ToString();
                //Console.WriteLine("starting on " + ip + " delay  " + sleep+".current status "+status);
                threads[i] = new Thread(PollingThreadStart);
                threads[i].Start(new MyThreadParameters(ip, sleep, status, host, port));
                threads[i].Name = host;

            }
            Thread.Sleep(50000);
        }

        while (true);
    }

6 个解决方案

#1


Killing threads forcibly is a bad idea. It can leave the system in an indeterminate state.

强行杀死线程是一个坏主意。它可以使系统处于不确定状态。

You should set a flag (in a thread-safe way) so that the thread will terminate itself appropriately next time it checks. See my threading article for more details and sample code.

您应该设置一个标志(以线程安全的方式),以便线程在下次检查时适当地自行终止。有关更多详细信息和示例代码,请参阅我的线程文章。

I would add that using Sleep is almost always the wrong thing to do, by the way. You should use something which allows for a graceful wake-up, such as Monitor.Wait. That way when there are changes (e.g. the polling thread should die) something can wake the thread up if it's waiting, and it can notice the change immediately.

我想补充一点,顺便说一句,使用Sleep几乎总是错误的做法。您应该使用允许优雅唤醒的内容,例如Monitor.Wait。这样当有变化时(例如,轮询线程应该死掉),如果等待,某些东西可以将线程唤醒,并且它可以立即注意到该变化。

#2


Given that most of your threads will spend the majority of their time doing nothing, your design might be better realised as a single thread that keeps a list of ip addresses and the time they're due to be polled next. Keep it sorted in order of next poll time.

鉴于您的大多数线程将大部分时间都不做任何事情,您的设计可能会更好地实现为保留IP地址列表的单个线程以及它们接下来要轮询的时间。保持按下次轮询时间顺序排序。

Pseudocode:

What time does the next ip address need to be polled?
Sleep till then
Poll the address.
Update the poll time for that address to now + interval.
Resort the list
Repeat.

Whenever you have a DB update, update the list and then order the thread to re-evaluate when it needs to stop.

每当您进行数据库更新时,请更新列表,然后命令线程在需要停止时重新评估。

#3


You don't specify the language you are targetting, but in general you use the same method regardless of the language. Simple use a shared variable that is used to signal the thread when it is time to stop running. The thread should periodically check the value and if it is set it will stop in a graceful fashion. Typically, this is the only safe method to stop a thread.

您没有指定要定位的语言,但通常无论语言如何都使用相同的方法。简单地使用一个共享变量,用于在线程停止运行时发出信号。线程应该定期检查值,如果设置它将以优雅的方式停止。通常,这是停止线程的唯一安全方法。

#4


I would say:

我会说:

  1. Don't kill threads. Ask them to die, nicely (vie Events or some shared flag).
  2. 不要杀死线程。让他们死,很好(与事件或一些共享旗帜竞争)。

  3. Be careful when creating exactly one thread per DB entry. This could mean that some unexpected DB activity where suddenly you have many rows translates into killing the OS with too many threads. Definitely have a limit on the number of threads.
  4. 每个数据库条目只创建一个线程时要小心。这可能意味着一些意外的数据库活动,突然你有很多行转换为用太多线程杀死操作系统。绝对有线程数限制。

#5


You could send an interrupt signal to the thead you want to end. The thread that has been signalled would need to catch the ThreadInterruptedException that will be raised, and exit gracefully.

您可以向要结束的thead发送中断信号。已发出信号的线程需要捕获将引发的ThreadInterruptedException,并正常退出。

There are other, possibly better, ways to achieve what you want, but they are more complicated...

还有其他可能更好的方法来实现你想要的东西,但它们更复杂......

#6


What you are trying to do is a bad idea because of the reasons mentioned above. However you can still give the thread a name which can be the host name. You may find out the thread by checking the name and kill it.

由于上述原因,你要做的是一个坏主意。但是,您仍然可以为线程指定一个可以作为主机名的名称。您可以通过检查名称找出该线程并将其删除。

#1


Killing threads forcibly is a bad idea. It can leave the system in an indeterminate state.

强行杀死线程是一个坏主意。它可以使系统处于不确定状态。

You should set a flag (in a thread-safe way) so that the thread will terminate itself appropriately next time it checks. See my threading article for more details and sample code.

您应该设置一个标志(以线程安全的方式),以便线程在下次检查时适当地自行终止。有关更多详细信息和示例代码,请参阅我的线程文章。

I would add that using Sleep is almost always the wrong thing to do, by the way. You should use something which allows for a graceful wake-up, such as Monitor.Wait. That way when there are changes (e.g. the polling thread should die) something can wake the thread up if it's waiting, and it can notice the change immediately.

我想补充一点,顺便说一句,使用Sleep几乎总是错误的做法。您应该使用允许优雅唤醒的内容,例如Monitor.Wait。这样当有变化时(例如,轮询线程应该死掉),如果等待,某些东西可以将线程唤醒,并且它可以立即注意到该变化。

#2


Given that most of your threads will spend the majority of their time doing nothing, your design might be better realised as a single thread that keeps a list of ip addresses and the time they're due to be polled next. Keep it sorted in order of next poll time.

鉴于您的大多数线程将大部分时间都不做任何事情,您的设计可能会更好地实现为保留IP地址列表的单个线程以及它们接下来要轮询的时间。保持按下次轮询时间顺序排序。

Pseudocode:

What time does the next ip address need to be polled?
Sleep till then
Poll the address.
Update the poll time for that address to now + interval.
Resort the list
Repeat.

Whenever you have a DB update, update the list and then order the thread to re-evaluate when it needs to stop.

每当您进行数据库更新时,请更新列表,然后命令线程在需要停止时重新评估。

#3


You don't specify the language you are targetting, but in general you use the same method regardless of the language. Simple use a shared variable that is used to signal the thread when it is time to stop running. The thread should periodically check the value and if it is set it will stop in a graceful fashion. Typically, this is the only safe method to stop a thread.

您没有指定要定位的语言,但通常无论语言如何都使用相同的方法。简单地使用一个共享变量,用于在线程停止运行时发出信号。线程应该定期检查值,如果设置它将以优雅的方式停止。通常,这是停止线程的唯一安全方法。

#4


I would say:

我会说:

  1. Don't kill threads. Ask them to die, nicely (vie Events or some shared flag).
  2. 不要杀死线程。让他们死,很好(与事件或一些共享旗帜竞争)。

  3. Be careful when creating exactly one thread per DB entry. This could mean that some unexpected DB activity where suddenly you have many rows translates into killing the OS with too many threads. Definitely have a limit on the number of threads.
  4. 每个数据库条目只创建一个线程时要小心。这可能意味着一些意外的数据库活动,突然你有很多行转换为用太多线程杀死操作系统。绝对有线程数限制。

#5


You could send an interrupt signal to the thead you want to end. The thread that has been signalled would need to catch the ThreadInterruptedException that will be raised, and exit gracefully.

您可以向要结束的thead发送中断信号。已发出信号的线程需要捕获将引发的ThreadInterruptedException,并正常退出。

There are other, possibly better, ways to achieve what you want, but they are more complicated...

还有其他可能更好的方法来实现你想要的东西,但它们更复杂......

#6


What you are trying to do is a bad idea because of the reasons mentioned above. However you can still give the thread a name which can be the host name. You may find out the thread by checking the name and kill it.

由于上述原因,你要做的是一个坏主意。但是,您仍然可以为线程指定一个可以作为主机名的名称。您可以通过检查名称找出该线程并将其删除。