从另一个线程开始一个线程 [英] start a thread from another thread

查看:113
本文介绍了从另一个线程开始一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是多线程技术的新手,我正在尝试使用C ++编写线程.

I am new to multithreading and I am experimenting with threads in C++.

到目前为止,我有:

一直运行并在击键时运行的线程1会终止设置repeat = 0的操作.

thread1 that runs all the time and on keystroke terminates setting repeat=0.

在repeat = 1时运行的线程2(因此,当线程1终止时,线程2也终止)

thread2 that runs while repeat=1 (so when thread1 terminates, thread 2 terminates too)

在满足条件的情况下从thread2内部开始的thread3进行stg,终止并再次在thread2内部重新启动.

thread3 that begins inside thread2 on a condition, does stg, terminates and restarts again inside thread2 if the condition is satisfied.

我没有任何问题,但是:

I don't have any problems but:

我想知道在一个线程中启动一个线程有多么好的策略.

I am wondering how good policy is to start a thread inside a thread.

thread3启动和终止多次.相比于每次创建一个新线程,启动线程,不时挂起和唤醒它会更好吗?

thread3 starts and terminates many times.  Is it better to start a thread, suspend and wake it up every now and then than creating everytime a new thread?

直觉上,我认为启动和终止线程是一种更干净的解决方案,但我不确定设置线程的成本

Intuitively I think that it is a more clean solution to start and terminating the thread but I am not sure about the cost of setting it up

推荐答案

阿曼达,

我建议的第一件事是,如果您使用的是.NET 4,则请切换出Task对象的Thread对象.与线程相比,实例化的任务要便宜得多.如果您需要有关任务并行库入门的信息 然后查看此链接:

The first thing that I'd recommend is that if you're using .NET 4 you switch out the Thread objects for the Task object. Tasks are much less expensive to instantiate than a Thread. If you need information on getting started with the Task Parallel Library then check out this link:

http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx

关于在线程(或Task中的Task)中启动新线程,这根本没有问题.关于暂停/恢复线程,为了以这种方式重用线程,您需要使其处于连续循环中.你不能打电话 在任何单个Thread实例上,Thread.Start()均不止一次.您可以使用一些标志来指示线程应执行某些操作,并且每当未设置该标志时,都应执行Thread.Sleep(100)以等待该标志再次被设置.但是我会 建议您切换到任务",然后在每次应执行操作时简单地启动一个新任务,这样可以使操作更整洁,并且您的开销也更少.

With regards to starting a new thread within a thread (or a Task within a Task), there's no problem at all with that. About suspending/resuming a thread, in order to re-use the thread in this way you'd need to have it in a continual loop. You can't call Thread.Start() more than once on any single Thread instance. You could use some flag to indicate that the thread should perform some action and whenever the flag is not set have it perform Thread.Sleep(100) to wait until the flag is set again. However I'd suggest you switch over to Tasks and then simply start a new Task every time the action should be performed, this way it will be cleaner and you'll have less overhead.

此致

泰勒


这篇关于从另一个线程开始一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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