Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Perl Thread

Shulou Source: shulou.com Published: 2022-06-02 07:56:54 09月28日 Update

Xiaobian to share with you Perl thread sample analysis, I hope you have something to gain after reading this article, let's discuss it together!

1: Creating Perl threads

usethreads;my$thr=threads->new(\&sub1);subsub1{print"Inthethreads";}

You can also create Perl threads by creating and passing parameters to Perl threads

new=create

my$thr=threads->create(\sub1,@paramlist);

2: Wait for the Perl thread to end

usethreads;my($thr)=threads->new(\sub1);my@return=$thr->join();subsub1{return('FiFty',1,2);}

Note that in this example, sub1 returns a list, so we need to use my($thr) when defining Perl threads, which is the context for giving $thr a list

3: Ignore a Perl thread

Join does three things: waits for a Perl thread to launch, cleans up Perl threads, and returns Perl thread returns.

If you are not interested in Perl threads, you can use detach to ignore them, Perl will automatically clean up the process.

usethreadsmy$thr=threads->create(\&sub1);$thr->detach();sleep(15);subsub1{my$a=0;while(1){$a++;print"\$ais$a\n";sleep1;}}

sleep's role here is to make the main process run longer, otherwise the Perl thread will exit if the main program is pushed out

We can also exit Perl threads in sub

subsub1{threads->detach();}

4: Data sharing

usethreads;usethreads::shared;my$foo:shared=1;my$bar=1;my$thr=threads->create(sub{$foo++;$bar++}->join();print$foo,"\n";#2print$bar,"\n";#1

Use hash as shared data to note

my$foo:shared;my$bar;my%foo;$foo->{bar}=\$bar#Error, references to shared data must be used

5: Problems with data sharing

Consider such a program

usethreads;usethreads::shared;my$a:shared=1;my$thr1=threads->create(\&sub1);my$thr2=threads->create(\&sub2);$thr1->join;$thr2->join;print("$a\n");subsub1{my$foo=$a;$a=$foo+1;}subsub2{my$bar=$a;$a=$bar+1;}

What is the value of a at this time? Sub1 and sub2 both modify the brightening a, so the value of a is uncertain, either 2 or 3 (I tried n times and it was 3)

6: Synchronization and control

Access control: lock()

After reading this article, I believe you have a certain understanding of "Perl thread sample analysis", if you want to know more related knowledge, welcome to pay attention to the industry information channel, thank you for reading!

Tags: Threads data examples analysis articles processes controls up and down context main program functions examples interests parameters can be passed done time time more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Tech Info vpn MySQL NVidia