Get the App
SLTechnology News&Howtos  ›  Development  › 

How do Perl threads die?

Shulou Source: shulou.com Published: 2022-06-02 07:56:23 10月02日 Update

This article mainly introduces how Perl threads die, has a certain reference value, interested friends can refer to, I hope you have a lot of gains after reading this article, let Xiaobian take you to understand.

Death of Perl threads

In most cases, you want the Perl thread you create to exit normally, which means that the Perl thread's corresponding function body returns and frees resources after execution. For example, in the example in Listing 5, the exit procedure after a new Perl thread is joined. However, if the mainline terminates prematurely due to improper detach or some unexpected exception, the Perl threads it created may not have finished executing, but they will still be forcibly aborted. You might get a warning like "Perplexed with active threads."

Of course, you can explicitly call exit() to end a Perl thread, but it's worth noting that by default, if you call exit() in a Perl thread, all other Perl threads will end with it, and in many cases, this may not be what you want. If you want exit() to work only in the Perl thread that called it, you need to set 'exit'=>'thread_only' when creating that Perl thread. for example

Listing 7. Setting the 'exit'=>'thread_only' attribute for a Perl thread

#!/ usr/bin/perl # usethreads; subsay_hello{ printf("Hellothread!@_.\ n"); sleep(10); printf("Bye\n"); } subquick_exit{ printf("Iwillbeexitinnotime\n"); exit(1); } my$t1=threads->create(\&say_hello,"param1","param2"); my$t2=threads->create({'exit'=>'thread_only'},\&quick_exit); $t1->join(); $t2->join();

If you want each Perl thread's exit method to be valid only for itself, then it's obviously a hassle to explicitly set the 'exit'=>'thread_only' attribute every time you create a new Perl thread, or you can set this attribute to be valid globally when you introduce the threads package, for example

Listing 8. Setting 'exit'=>'thread_only' to global properties

usethreads('exit'=>'threads_only'); subfunc{ ... if($condition){ exit(1); } } my$t1=threads->create(\&func); my$t2=threads->create(\&func); $t1->join(); $t2->join(); Thank you for reading this article carefully. I hope that the article "How Perl Threads Die" shared by Xiaobian will be helpful to everyone. At the same time, I hope that everyone will support it a lot. Pay attention to the industry information channel. More relevant knowledge is waiting for you to learn!

Tags: Thread property method article situation time list valid global inappropriate accident hair will be attached skin does not exist main line value interest function at the same time not yet meaning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MariaDB MySQL Docker NVidia