15

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 script call itself after every 3 seconds. But i need to call it every second , can anybody provide me a solution to it or point me to right direction.

#!usr/bin/perl
use warnings;

sub print
{
local $gg = time;
print "$gg\n";
}

$oldtime = (time + 1);
while(1)
{
if(time > $oldtime)
{
    &print();
    sleep 2;
    $oldtime = (time + 1);
            }
        }

Its just an example.

1 Answer 1

42

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).
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. To you know what is a good source for understanding threads in terms of multiple threads reading and writing the same global variables at the same time?
@Myforwik, please see the update to the answer. Variables are not shared between threads. You need to use threads::shared for that. The two documentation links I added to the answer should help with understanding that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.