Consider the following code:
for (my $i = 0; $i < $threadCount; $i++) {
if($isResumed) {
# TODO: load stats from DB
}
else {
$stats->{workers}->{$i} = &share({});
$stats->{workers}->{$i}->{tid} = undef;
$stats->{workers}->{$i}->{foo} = "bar";
$stats->{workers}->{$i}->{abc} = 123;
}
# create the worker thread
my $thr = threads->create(\&worker);
# TODO: find a way to store the TID in the $i slot. why have two differetn IDs?
$stats->{workers}->{$i}->{tid} = $thr->tid();
}
I am using the $stats hash to hold data that should be shared between threads, as well as data about what each thread is doing. The problem I have is that I would like to reference the thread data in this hash based on the TID, not an arbitrary value assigned by $i in the loop.
When I create the thread, the work starts immediately, but it cannot start its work until the hash values are set. So, if I do:
$thr = threads->create(\&worker);
$stats->{workers}->{$thr->tid()} = &share({});
It will not work because not all the data it needs is set yet.
So basically, is there a way for me to create a thread, but defer it from running its code until I specifically tell it to? Something like:
$thr = threads->create(\&worker);
$stats->{workers}->{$thr->tid()} = &share({});
$thr->start();
In the end, after reviewing my code; I realized that I was over complicating it, and did not truly need to know the TIDs.
I ended up just passing the relevant data to the worker subroutine during the create statement.
That being said though, People who come across this question should take a look at Jean’s answer, as it appears to be a promising solution to my original problem.