Multithreading for perl code

前端 未结 1 1246
自闭症患者
自闭症患者 2021-02-13 09:41

I need to know how to implement multi threading for the following code . I need to call this script every second but the sleep timer processes it after 2 seconds . In total scri

相关标签:
1条回答
  • 2021-02-13 10:14

    Here is a simple example of using threads:

    use strict;
    use warnings;
    use threads;
    
    sub threaded_task {
        threads->create(sub { 
            my $thr_id = threads->self->tid;
            print "Starting thread $thr_id\n";
            sleep 2; 
            print "Ending thread $thr_id\n";
            threads->detach(); #End thread.
        });
    }
    
    while (1)
    {
        threaded_task();
        sleep 1;
    }
    

    This will create a thread every second. The thread itself lasts two seconds.

    To learn more about threads, please see the documentation. An important consideration is that variables are not shared between threads. Duplicate copies of all your variables are made when you start a new thread.

    If you need shared variables, look into threads::shared.

    However, please note that the correct design depends on what you are actually trying to do. Which isn't clear from your question.

    Some other comments on your code:

    • Always use strict; to help you use best practices in your code.
    • The correct way to declare a lexical variable is my $gg; rather than local $gg;. local doesn't actually create a lexical variable; it gives a localized value to a global variable. It is not something you will need to use very often.
    • Avoid giving subroutines the same name as system functions (e.g. print). This is confusing.
    • It is not recommended to use & before calling subroutines (in your case it was necessary because of conflict with a system function name, but as I said, that should be avoided).
    0 讨论(0)
提交回复
热议问题