简体   繁体   English

在另一个线程中调用函数是否安全?

[英]Is it safe to call a function in another thread?

I don't know much about threads, but I have a function in the main class of my console application called SendProcessCmd(string cmd). 我对线程了解不多,但是在控制台应用程序的主类中有一个名为SendProcessCmd(string cmd)的函数。 In my main() I create a process, and store the StreamWriter as a class member var, and my SendProcessCmd() issues the .WriteLine() commands to it. 在我的main()中,我创建一个进程,并将StreamWriter存储为类成员var,然后我的SendProcessCmd()向其发出.WriteLine()命令。

I have another thread with a TCP server that listens for connections, then allows these to send commands to the process using Program.SendProcessCmd(). 我还有一个带有TCP服务器的线程,该线程侦听连接,然后允许它们使用Program.SendProcessCmd()将命令发送到进程。 Is it safe to do this? 这样安全吗?

The safest method I can think of would be to find the running process in my server's thread, create a new StreamWriter, then issue the commands. 我能想到的最安全的方法是在服务器线程中找到正在运行的进程,创建一个新的StreamWriter,然后发出命令。 However, this seems like a rather long way around to do the same thing. 但是,这似乎需要很长的路要走。

The whole purpose of threads is that you can always call any function and access any data structure from any thread. 线程的全部目的是,您始终可以调用任何函数并从任何线程访问任何数据结构。 There are gotcha's, though: 但是有一些陷阱:

  1. You should always consider concurrency issues, locking and dead-lock avoiding etc. 您应始终考虑并发问题,避免发生锁和死锁等。
  2. Some functions and data structures (esp. related to Windows programming) cannot be called/accessed from a thread other than the main UI thread; 某些功能和数据结构(尤其是与Windows编程有关的功能)不能从主UI线程以外的其他线程调用/访问。 doing so may crash your program or cause an exception 这样做可能会使您的程序崩溃或导致异常

If I have understood you correctly, it sounds like both threads will be using the same StreamWriter. 如果我对您的理解正确,听起来这两个线程将使用相同的StreamWriter。 If that is correct, then you will need to at the very least synchronise the writes to the StreamWriter using a Monitor . 如果这是正确的,那么您至少需要使用Monitor同步到StreamWriter的写入。

If each thread is using multiple calls to the Write method to build up a complete message you need to block other threads from writting for the entire duration that it takes to complete the component parts of the message otherwise your message components will become mixed-up, it is like having two people trying to write on the same piece of paper at the same time in the same location, each writting a different story. 如果每个线程正在使用多次调用Write方法来构建完整的消息,则需要在完成消息的各个组成部分的整个过程中阻止其他线程进行写操作,否则消息组件将变得混乱不堪,就像有两个人试图在同一时间在同一位置的同一张纸上写字,每个人写的故事不同。

Executing any code and accessing memory is all perfectly fine for any number of threads to do simultaneously. 对于任何数量的线程同时执行,执行任何代码和访问内存都非常好。 The thing you have to watch out for is two threads trying to write to the same area of memory 您需要注意的是两个线程试图写入相同的内存区域

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM