Здравствуйте, гость ( Вход | Регистрация )

 
Ответить в эту темуОткрыть новую тему
> Multiple parallel execution of a function, Множественное параллельное выполнение функции
neves
сообщение 8.11.2020, 1:31
Сообщение #1


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Is it possible to run multiple parallel functions from one script?
For example, I have this function:
Код
function start_notepad()
  wait(500)
  exec ([[notepad.exe]])
  wait(500)
end


If I try to use it like this:
Код
for i = 1, 5 do
    start_notepad()
end

won't actually start multiple parallel asynchronous notepads, but will start them one by one.

Is it possible to do this without importing additional libraries? Or maybe to be simulated somehow?
I tried to do it using coroutines, but their purpose is a bit different.
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
DarkMaster
сообщение 8.11.2020, 8:46
Сообщение #2


***********

Модератор UOPilot
Сообщений: 9.465
Регистрация: 2.12.2008
Группа: Супермодераторы
Наличность: 27679
Пользователь №: 11.279



https://coco.luajit.org/index.html
https://www.tutorialspoint.com/lua/lua_coroutines.htm

Side solution:
https://luapower.com/pthread


--------------------
Скрипты UOPilot под заказ.
Консультации по UOpilot 15$/час.
Услуги Lua разработчика (не пилот, проекты, постоянка)
Disсоrd:
Kov____
Пользователь в онлайне!Delete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 8.11.2020, 14:01
Сообщение #3


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 8.11.2020, 1:31) *

Is it possible to run multiple parallel functions from one script?

Of course. You can use multithreading easely via -parallel.

Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('void',{[[#}
#
workflow StartMyApp($app, $count){#}
    foreach –parallel ($i in 1..$count){#}
        start $app
    }
}

StartMyApp notepad 3
#
]]})

This code will open 3 notepads concurrently.


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 8.11.2020, 23:42
Сообщение #4


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(DarkMaster @ 8.11.2020, 8:46) *

I already tried to solve the problem with coroutines, but ain't works as I expect.
>>
Код
co1 = coroutine.create(
    function()
        for i = 1, 100 do
            print(i)
            coroutine.yield(co1)
        end
    end
)

co2 = coroutine.create(
    function()
        for i = 1, 100 do
            print(i)
            coroutine.yield(co2)
        end
    end
)

for i = 1, 100 do
    coroutine.resume(co1)
    coroutine.resume(co2)
end

This was the closest solution, but still ain't works as I expect. They ain't parallel.
Цитата(DarkMaster @ 8.11.2020, 8:46) *

I'll check this out. Can you give me an example of parallel usage with pthread.

Цитата(Fors1k @ 8.11.2020, 14:01) *

Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('void',{[[#}
#
workflow StartMyApp($app, $count){#}
    foreach –parallel ($i in 1..$count){#}
        start $app
    }
}

StartMyApp notepad 3
#
]]})

This code will open 3 notepads concurrently.

Yes, but what if I have much longer function, not just to open one notepad multiple times.
For example if I want to open multiple .doc files and write different text in each document?
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
DarkMaster
сообщение 9.11.2020, 4:44
Сообщение #5


***********

Модератор UOPilot
Сообщений: 9.465
Регистрация: 2.12.2008
Группа: Супермодераторы
Наличность: 27679
Пользователь №: 11.279



It simple example, BUT uopilot rly dont like that. When i stop script, it crash pilot.

You need to be ready for some problems with some functions. If function demand workwindow and dont have handle like param of function, idk how pilot will work with that (mb all be ok, but i rly dont know).


Код
local pthread = require[[luaPlugins\pthread\pthread]]

log(pthread)


local t_function = function(handle)
    --workwindow(handle)
    while 1 do
        --send(handle..'\n')
        log(1)
        wait(1000)
    end
end


local thread_1 = pthread.new(t_function)
wait(2000)
local thread_2 = pthread.new(t_function)


Сообщение отредактировал DarkMaster - 9.11.2020, 4:59


--------------------
Скрипты UOPilot под заказ.
Консультации по UOpilot 15$/час.
Услуги Lua разработчика (не пилот, проекты, постоянка)
Disсоrd:
Kov____
Пользователь в онлайне!Delete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
DarkMaster
сообщение 9.11.2020, 5:08
Сообщение #6


***********

Модератор UOPilot
Сообщений: 9.465
Регистрация: 2.12.2008
Группа: Супермодераторы
Наличность: 27679
Пользователь №: 11.279



It works in pure luajit from luapower.com. I didnt test it in pilot.

Код
thread = require[[thread]]
socket = require[[socket]]

t_function = function(var)
    socket = require[[socket]]
    while 1 do
        print(var)
        socket.sleep(1)
    end
end

thread_1 = thread.new(t_function, 1)
socket.sleep(0.5)
thread_2 = thread.new(t_function, 2)



// thread require pthread

Сообщение отредактировал DarkMaster - 9.11.2020, 6:41


--------------------
Скрипты UOPilot под заказ.
Консультации по UOpilot 15$/час.
Услуги Lua разработчика (не пилот, проекты, постоянка)
Disсоrd:
Kov____
Пользователь в онлайне!Delete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 9.11.2020, 12:39
Сообщение #7


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 8.11.2020, 23:42) *

Yes, but what if I have much longer function, not just to open one notepad multiple times.
For example if I want to open multiple .doc files and write different text in each document?

I gave a solution to the task, that you provided)
Show me your current script, which doing this without parallel. That can help me to give solution, cause i'm not a clairvoyant=)
Or describe ur issue. For example:
I have folder with 100 .doc files(ex1.doc;ex2.doc;...). And i have one .txt file, with 100 strings. I want to append each string to each .doc file. (first string -> ex1.doc, etc.).

Сообщение отредактировал Fors1k - 9.11.2020, 12:39


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 9.11.2020, 15:52
Сообщение #8


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 8.11.2020, 23:42) *

open multiple .doc files and write different text in each document

For test, firstly, lets crate 20 .doc files with "start" text in each
Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('return',{[[#}
#
$path = 'C:\files\word'

$word = New-Object -ComObject Word.Application
$doc = $word.Documents.Add()
$Selection = $word.Selection
$Selection.TypeText("Start")
$Selection.TypeParagraph()
1..20|%{$doc.SaveAs("$path\test$_.doc")}
$Word.Quit()
[Runtime.InteropServices.Marshal]::ReleaseComObject($word)
msg_box "Done!"
#
]]})


Now lets append to each document "string №"
code
Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('return',{[[#}
#
$path = 'C:\files\word'

$files = ((gci $path)|sort {[int]($_.name -replace"\D+")}).fullname

$Strings = 1..20|%{$i=1}{"string $i";$i++}

function WriteToDoc($file, $text, $word){#}
    $Document = $word.Documents.Open($file)
    $Selection = $word.Selection
    $Selection.EndKey(6, 0)
    $Selection.TypeText("$text`r`n")
    $Document.close()
}

$Word = New-Object -ComObject Word.Application

for($i=0;$i -lt $files.count;$i++){#}
    WriteToDoc $files[$i] $Strings[$i] $word
}

$Word.Quit()
[Runtime.InteropServices.Marshal]::ReleaseComObject($word)
msg_box "Done!"
log
#
]]})

Ask me, if u have questions or give description of your task.


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 9.11.2020, 19:26
Сообщение #9


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(DarkMaster @ 9.11.2020, 5:08) *

Код
thread = require[[thread]]
socket = require[[socket]]

t_function = function(var)
    socket = require[[socket]]
    while 1 do
        print(var)
        socket.sleep(1)
    end
end

thread_1 = thread.new(t_function, 1)
socket.sleep(0.5)
thread_2 = thread.new(t_function, 2)



Awesome! I faced some issues, but I'll figure them alone.

Цитата(Fors1k @ 9.11.2020, 12:39) *

I gave a solution to the task, that you provided)

Yes, I tried to give minimal example, to be more clear what my goal is. The real script is more longer and takes more time to execute.

Цитата(Fors1k @ 9.11.2020, 15:52) *

Ask me, if u have questions or give description of your task.

I tested -parallel and it is the exact thing I need, works awesome, but do I have to rewrite my whole lua function which I want to parallelize to posh script?
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 9.11.2020, 20:32
Сообщение #10


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 9.11.2020, 19:26) *

I tested -parallel and it is the exact thing I need, works awesome

You are welcome)
Btw, there is not only one way of multithreading.
Цитата(neves @ 9.11.2020, 19:26) *

Do I have to rewrite my whole lua function which I want to parallelize to posh script?

I dont know, cuz i dont see your function=)
May be we will have to rewrite only some "heavy" part. Often 20 lines on lua = couple lines on posh, so i think it wont be a problem, i'll help.

Btw, did script above help you to write text in .doc?


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 9.11.2020, 22:32
Сообщение #11


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(Fors1k @ 9.11.2020, 20:32) *

I dont know, cuz i dont see your function=)
May be we will have to rewrite only some "heavy" part. Often 20 lines on lua = couple lines on posh, so i think it wont be a problem, i'll help.

This is a function I need to parallelize:
Код
function start_game()
  exec ([[F:\Games\OL\game.bat]])
  while workwinpid == nil do
    workwinpid = findwindow('Starting')
  end
  workwindow(workwinpid[1][1])
  while getwindowtext(workwinpid[1][1]) == 'Starting' do
    wait(500)
  end
  return workwinpid[1][1]
end

The task with .doc files was just an example, I have to start 10 game clients and write text in them parallelized.
So I gave this .doc example cuz its easier to recreate.
Цитата(Fors1k @ 9.11.2020, 20:32) *

Btw, did script above help you to write text in .doc?

Yes, all worked good. Created 20 test1-20.doc files.
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 9.11.2020, 23:29
Сообщение #12


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 9.11.2020, 22:32) *

This is a function I need to parallelize:

Ok, i'll check this out at morning.
And show pls content of this bat "F:\Games\OL\game.bat".


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 9.11.2020, 23:54
Сообщение #13


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(Fors1k @ 9.11.2020, 23:29) *

And show pls content of this bat "F:\Games\OL\game.bat".

The .bat only starts an .exe file.
Код
start game.exe ur;
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 10.11.2020, 13:06
Сообщение #14


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 9.11.2020, 22:32) *

This is a function I need to parallelize:

As i understand, you need to launch the game, for example, 3 times, and wait until all of them will finish starting process. Main window title must become not equals "Starting".
I solved this with parallel and without.
Here is code without parallel.
code
Код
--lua
require"luaposh";log"clear";log"mode compact"
handles=PScode('return',{[[#}
#
$path = 'F:\Games\OL\game.exe'

function Start_game($app, $repeat){#}
    $title = "Starting"
    $apps+=1..$repeat|forEach{#}
        start $app -ArgumentList "ur" -PassThru
    }
    $handles+=$apps|forEach{#}
        while($_.MainWindowHandle -eq 0){ sleep -m 1 }
        $handle = $_.MainWindowHandle
        while($_.MainWindowTitle -eq $title){ $_.Refresh();sleep -m 500 }
        $handle
    }
    return $handles
}

$return = Start_game $path 3
#
]]})
log(handles)

Because posh can work with objects, we can avoid necessity of using parallel. Tell me, if you need description of this code. In two words, we start app 3 times and collect objects of their processes. Now we wait window appearing, then we wait window title changing for each process we launched. As i understand, that way will solve ur problem, if not, i'll give u code with parallel.


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 11.11.2020, 0:58
Сообщение #15


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(Fors1k @ 10.11.2020, 13:06) *

As i understand, you need to launch the game, for example, 3 times, and wait until all of them will finish starting process.

Yes, that's the exact thing I wanna do. And after they finished starting process I wanna write different text in each window.
Цитата(Fors1k @ 10.11.2020, 13:06) *

Because posh can work with objects, we can avoid necessity of using parallel. Tell me, if you need description of this code. In two words, we start app 3 times and collect objects of their processes. Now we wait window appearing, then we wait window title changing for each process we launched. As i understand, that way will solve ur problem, if not, i'll give u code with parallel.

Yes, actually this can be solved that way, without using parallelization, but after the games are already started I have to write different text in all of them parallel.

Can you give me such parallel solution in posh:
1. Starting 3 games.
2. Wait for window appearing.
3. Wait window title changing.
4. After title is changed sends different text in each window.
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 11.11.2020, 19:19
Сообщение #16


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Sorry, was busy today.
Did above script complete steps 1-3 correctly? Function Start_game is good?
Show me code of step 4. I need to understand what we have to do)


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 12.11.2020, 1:51
Сообщение #17


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(Fors1k @ 11.11.2020, 19:19) *

Did above script complete steps 1-3 correctly? Function Start_game is good?

Yes, it starts 3 game launchers, but ain't return anything. I tried with Write-Output $handles instead of return $handles. Anyways this isn't much important actually. The main function seems to work alright.
Цитата(Fors1k @ 11.11.2020, 19:19) *

Show me code of step 4. I need to understand what we have to do)

The fourth step is only to send different text to each game parallely, after it finished loading.
For example sending string from this table parallel to each game:
script
Код

--lua
_list = {
{'send this to game 1'},
{'send this to game 2'},
{'send this to game 3'}
}

function start_game(text)
  exec ([[F:\Games\OL\game.bat]])             --start an exe file
  workwinpid = findwindow('Starting')
  while workwinpid == nil do       --wait until game window appear
    workwinpid = findwindow('Starting')
  end
  workwindow(workwinpid[1][1])
  while getwindowtext(workwinpid[1][1]) == 'Starting' do            --wait until the process isn't finished starting
    wait(500)
  end
  send(text)                 --after the process loaded successfully send text
  wait("1s")
  terminate(getwindowtext (workwindow()))
  wait("1s")
end

for i = 1, 3 do
    start_game(_list[i][1])
end

This example starts one [[F:\Games\OL\game.bat]] and waits for loading process finishing. Then sends text from table _list, and then terminate the window.
All this process has to be parallelized.
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 12.11.2020, 17:46
Сообщение #18


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Lets firstly test one flow.
Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('return',{[[#}
#
$title = "Starting"
$path  = 'F:\Games\OL\game.exe'
$proc  = Start -PassThru $path
while($proc.MainWindowHandle -eq 0){
    sleep -m 1
}
$handle = $proc.MainWindowHandle
$proc.Refresh()
while($proc.MainWindowTitle -eq $title){
    $proc.Refresh()
    sleep -m 500
}
log "Handle= $handle"

Send-Text $handle "test"
log
#
]]})

You should specify path to .exe, not to .bat. Try this code, check handle in log.
Before run this code, update luaposh.

Сообщение отредактировал Fors1k - 12.11.2020, 17:48


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
neves
сообщение 13.11.2020, 11:02
Сообщение #19


***

Novice
Сообщений: 64
Регистрация: 4.10.2019
Группа: Пользователи
Наличность: 0
Пользователь №: 19.419
Возраст: 19



Цитата(Fors1k @ 12.11.2020, 17:46) *

script
Код
--lua
require"luaposh";log"clear";log"mode compact"
PScode('return',{[[#}
#
$title = "Starting"
$path  = 'F:\Games\OL\game.exe'
$proc  = Start -PassThru $path
while($proc.MainWindowHandle -eq 0){
    sleep -m 1
}
$handle = $proc.MainWindowHandle
$proc.Refresh()
while($proc.MainWindowTitle -eq $title){
    $proc.Refresh()
    sleep -m 500
}
log "Handle= $handle"

Send-Text $handle "test"
log
#
]]})


Returns
Цитата
Handle= 327762
Send-Text : The term 'Send-Text' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:18 char:1
+ Send-Text $handle "test"
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Send-Text:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Am I doing something wrong? I have the last luaposh version. (IMG:style_emoticons/default/unsure.gif)
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
Fors1k
сообщение 13.11.2020, 12:50
Сообщение #20


*****

Journeyman
Сообщений: 497
Регистрация: 19.12.2017
Группа: Пользователи
Наличность: 2399
Пользователь №: 18.746



Цитата(neves @ 13.11.2020, 11:02) *

Handle= 327762

Good.
Цитата(neves @ 13.11.2020, 11:02) *

Am I doing something wrong? I have the last luaposh version. (IMG:style_emoticons/default/unsure.gif)

This code require 7.7 version.
Check yours:
Код
--lua
log "clear";require "luaposh"
PScode('void',{[[version]]})


Сообщение отредактировал Fors1k - 13.11.2020, 12:50


--------------------
Для связиИзображение
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения

Ответить в эту темуОткрыть новую тему
2 чел. читают эту тему (гостей: 2, скрытых пользователей: 0)
Пользователей: 0

 

- Текстовая версия | Версия для КПК Сейчас: 18.4.2024, 15:59
Designed by Nickostyle