gpt4 book ai didi

multithreading - 套接字 : how execute two threads simultaneously without stop?

转载 作者:行者123 更新时间:2023-12-03 19:49:32 24 4
gpt4 key购买 nike

在客户端-服务器之间的套接字连接中,我在一个线程中(在一个循环中)接收有关远程 pc 的信息以及另一个线程中的其他特定信息。

我的问题是因为当创建第二个线程时,第一个线程会立即停止,但是我想使用第二个线程接收的信息是必要的循环,如下所示的代码。

那么,如何在不停止某个线程的情况下同时执行两个线程呢?

    // Entry point of first thread

procedure TSock_Thread2.Execute;
var
s: String;

begin
inherited;

while not Terminated and Socket.Connected do
begin
if Socket.ReceiveLength > 0 then
begin
s := Socket.ReceiveText;

if Pos('<|CUR|>', s)>0 then begin

TSTMouse := TSock_Thread5.Create(Socket);
TSTMouse.Resume;

Socket.SendText('<|GETCURSORICON|>'); // after this line, TSock_Thread2 stop your execution

end;

end;
end;



// Entry point of second Thread

procedure TSock_Thread5.Execute;
var
s, Ponteiro: string;

begin
inherited;

while not Terminated and Socket.Connected do
begin

if Socket.ReceiveLength > 0 then
begin
s := Socket.ReceiveText;

if Pos('<|MOUSEICON|>', s) > 0 then // receiving mouse icon here
begin

Delete(s, 1, Pos('<|MOUSEICON|>', s) + 12);
Ponteiro := Copy(s, 1, Pos('<|>', s) - 1);

if Ponteiro <> '' then

(Form1.LV1.Selected.SubItems.Objects[2] as TForm2).lblPoint.Caption := Ponteiro;

Sleep(100);
Socket.SendText('<|GETCURSORICON|>'); // request cursor icon again

end;

end;
end;

end;

最佳答案

你有两个线程从一个套接字读取?从一开始这通常是一个坏主意。如果你真的想要那样,那么你不能让它们同时读取,因为这不是套接字的工作方式。

任何给定的阅读器只能读取下一个字节或字节序列。没有内置控件可以说明为哪个线程指定了哪些字节。您需要弄清楚如何同步两个线程,以便它们各自知道何时允许读取。

另一个想法是只有一个线程从套接字读取。该线程可以读取字节序列,然后将它们分派(dispatch)给其他线程进行处理。

关于multithreading - 套接字 : how execute two threads simultaneously without stop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com