线程逻辑 - 它是如何工作的? [英] threading Logic - how is it working ?

查看:65
本文介绍了线程逻辑 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个基本的线程程序来理解线程是如何工作的。

然而我得到的结果并不是我所期望的[就像我知道结果会是什么.. lol:p ]

这里是代码



 class Program 
{
public Thread myThread;
string myName;

public Program(字符串名称)
{
myName = name;
myThread = new Thread(new ThreadStart(WorkerMethod));
}

private void WorkerMethod()
{
Console.WriteLine(Hello,);
Thread.Sleep(1500);
Console.WriteLine(myName);
}
static void Main(string [] args)
{


程序objProg1 =新程序(James);
计划objProg2 =新计划(债券);
objProg1.myThread.Start();
objProg2.myThread.Start();
Console.ReadLine();
}


}





告诉我,我所理解的是错误的。

在ObjProg1的主线程中启动,在ObjProg2的线程启动之后。

所以我认为首先调用ObjProg1的Hello然后线程进入休眠状态并执行传递到这里的ObjProg2再次调用Hello然后线程进入休眠状态,执行返回到objProg1,并且应该打印出James并在那之后粘贴。



所以根据我的结果理解[或误解]应该像

你好,

你好,

詹姆斯

债券



但是我看到的结果是

你好,

你好,

债券

詹姆斯



提醒!!!



现在我已经重新开始了应用程序结果就像我期待的那样。

所以基本上发生的事情是每次结果都不同。



请帮助我理解它是如何工作的以及为什么结果每次都不同。

解决方案

这是因为你无法保证线程的顺序是什么即将执行.Windows安排线程在需要时运行,而不是当你认为它们将要执行时。



你在想你的线程您的应用程序是系统中唯一运行的应用程序。事实是你的线程只有3个在他们的海洋。打开任务管理器,选择查看,选择列....打开线程列,查看在应用程序运行的同时系统中运行的线程数。在我的机器上,现在有大约1,400个线程在运行。



线程在有机会时运行,不一定按照你启动它们的顺序运行。

您的错误在于,您假设线程以您创建程序类的顺序同步启动。

实际上您只是委托到系统,你想要启动一个线程,并立即启动第二个线程。

如果你这样做的话,根本无法保证第一个线程在第二个线程之前启动并运行。



有很多方法可以同步它。



对于这个小型演示,我给你一个秘密:)

一个线程有一个 ThreadState 属性,你可以看到,如果它正在运行。



所以,如果你只是在你的两个线程启动之间放置那个小 ...,你强制程序等到第一个线程进入跑步的ate,在第二个线程开始之前。

然后你将总是有hello,hello,james bond输出。



程序objProg1 = 程序( 詹姆斯); 
程序objProg2 = 程序( Bond );
objProg1.myThread.Start();
while (objProg1.myThread.ThreadState!= ThreadState.Running);
objProg2.myThread.Start() ;
Console.ReadLine();





亲切的问候,迈克


为什么会你假设在两个具有相同优先级的线程中执行任何特定的执行顺序? Windows是抢占式多任务系统,因此它可以在执行中的任何时刻启动和停止线程,并允许任何其他线程或任务接管,前提是它没有阻塞或等待特定事件发生。 />


根据系统负载和可用内核数量,您甚至不能保证在执行线程之前打印Hello字样。停止,第二个线程开始。所以很有可能在某些时候你可以获得

 HHeelllloo ,, 

JBonamd
es

而不是你期望的输出。



线程是一个困难的概念,很难从琐碎的例子中弄清楚发生了什么,因为它们不是t持续足够长的时间来真正展示正在发生的事情。



我建议你尝试使用BackgroundWorker而不是裸线程它更容易做一些事情 - 例如他们有内置的进度报告 - 并使用更长的运行任务,通过进展报告你的主线程。

尝试让一个线程查看文件夹中的所有文件(以及它的子目录)并为它找到的每个文件名发出进度。而另一个像Fibonacci序列那样处理更多CPU密集的事情,并通过进度事件报告回来。

进度事件将在主线程中排队,然后逐个打印它们你应该看到从运行到运行输出不一致,但三个线程完全独​​立工作。


I have created a basic thread program to understand how threads work.
however the result that i am getting is not what i expected [ like i knew what the result will be .. lol :p]
here is the code

class Program
    {
        public Thread myThread;
        string myName;

        public Program( string name)
        {
            myName = name;
            myThread = new Thread(new ThreadStart(WorkerMethod));
        }

        private void WorkerMethod()
        {
            Console.WriteLine("Hello , ");
            Thread.Sleep(1500);
            Console.WriteLine(myName);
        }
        static void Main(string[] args)
        {
           

            Program objProg1 = new Program("James");
            Program objProg2 = new Program("Bond");
            objProg1.myThread.Start();
            objProg2.myThread.Start();
            Console.ReadLine();
        }

       
    }



Tell me that what i am understand is wrong.
In the main thread of ObjProg1 starts , after that thread of ObjProg2 starts.
so i think first Hello for ObjProg1 is called then thread goes to sleep and execution passes on to ObjProg2 here Hello is called again and the thread goes to sleep now the execution returns to objProg1 and James should be printed and after that Bond .

so result according to my Understanding [or Misunderstanding] should be like
Hello,
Hello,
James
Bond

but the result that i am seeing is
Hello,
Hello,
Bond
James

Alert !!!

Now that i have re run the application the result is as i was expecting it.
so basically what's happening is that result is different everytime.

Please help me understand how it is working and why the results are different everytime.

解决方案

This happens because you can't guarantee which order the thread are going to execute in. Windows schedules threads to run whenever it needs them to, not when you think they are going to execute.

You're thinking of your threads in your application as the only ones running in the system. Fact is your threads are just 3 in a sea of them. Open Task Manager, select View, Select columns.... Turn on the Threads column and see how many threads are running in the system at the same time your app is running. On my machine, right now, there's about 1,400 threads running.

Threads run whenever they get a chance to, not necessarily in the order you launched them.


Your "error" in thinking is, that you assume that the threads start synchronously in the order you create your program classes.
In fact you only "delegate" to the system, that you want to start a thread, and immediately a second thread.
There is simply no guarantee that the first thread will be up and running before the second thread if you do it this way.

There are lots of ways to synchronize that.

For this small demo, I show you a secret :)
A Thread has a "ThreadState" property where you can see, if it is running.

So, if you just put that little while... between your two thread starts, you force the program to wait until the first thread is in running state, before the second thread gets started.
Then you will always have the hello,hello,james bond output.

Program objProg1 = new Program("James");
				Program objProg2 = new Program("Bond");
				objProg1.myThread.Start();
				while (objProg1.myThread.ThreadState != ThreadState.Running) ;
				objProg2.myThread.Start();
				Console.ReadLine();



Kind regards, Mike


Why would you assume any specific order of execution in two threads of the same priority? Windows is a preemptive multitasking system, so it can start and stop threads at any point in their execution, and allow any other thread or task to take over, provided it isn't "Blocked" or waiting for something specific to happen.

Depending on the load on your system, and the number of cores available, you aren't even guaranteed to get the whole word "Hello," printed before the thread execution is stopped and the second thread starts. So it's quite possible that at some point you could get

HHeelllloo,,

JBonamd
es

instead of the output you expect.

Threads are a difficult concept, and it's very difficult to "work out what is happening" from trivial examples, because they don't last long enough to really demonstrate what is going on.

What I'd suggest is that you try using a BackgroundWorker instead of a "naked" thread as they make it easier to do some things - for example they have progress reporting built in - and use longer running tasks which report via progress to your main thread.
Try having one thread looking at all the files in a folder (and it's subdirectories) and issuing a "progress" for each file name it finds. And another working out something more CPU intensive like a Fibonacci sequence and reporting that back via progress events.
The progress events will queue in the "main" thread which then prints them one by one and you should see that the output is not consistent from run to run, but that the three threads work completely independently.


这篇关于线程逻辑 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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