Implementing thread in UNIX

Hi

For our load testing , we are using stubs (unix shell script) which send the response to the request coming from the application. As the unix stub is single threaded , it is responding to only one request whereas multiple requests come in parallely.

I haven't worked on thread concepts till now. Would like to know if multithreading can be achieved in shell script for e.g if i start up the shell script process, multi thread can handle the parallel requests coming in and send response parallely.

Would be fo great if sample code snippet is given. Thanks in advance.

Please note that while posting, you might want to post your environment like the U*IX variant you are using and also the shell you are using.

Assuming, you are using POSIX compliant shell like Bash or KSH, you can implement threads by forking processes using & operator:

thread () {
           # your thread code goes here
}

for i in {1..5}; do
          thread &
done

This forks 5 processes (or threads) with the same code.

1 Like

Thanks a lot for this snippet.

I tried one sample program like below:

 
#!/bin/ksh
date=`date +%y%m%d%H%M%S`
thread() {
echo "test" >> /tmp.txt
echo $date >> /tmp.txt // This to get the time logged for different iterations and see if all processed at same time
}
for i in {1..5}; do
thread &
done

In the output file - i could see the values written only for the 1st iteration but not for the subsequent iteration. :frowning:
Does this mean the shell is non-POSIX compliant? or how to test whether it is POSIX compliant and whether it works for the sample script.
Does my sample program makes any sense for testing this functionality and if it is how to confirm that multi-threading is acheived using a sample script?

You need to put a wait statement after the done statement:

done
wait

Tried putting wait . Still its not working :frowning:

What output do you get?
By the way, shell does not support multithreading just multitasking (by forking processes). If you are using ksh88, it is not fully POSIX compliant, ksh93 would be. But I think this should work in ksh88 too. Your temporary file is in an awkward directory (the root directory) can you write there? In shell you use # for comments, not // .

{1..5} is not POSIX. You would need something like this:

i=0;
while [ $((i+=1)) -le 5 ]; do
  thread &
done
wait

or

for i in 1 2 3 4 5; do

Otherwise the shell would execute the loop only once.