0

Lets assume the following situation:

function add_to_list
{
    thelist="$thelist $$"
}

for i in $(seq 1 100); do
    add_to_list&
done

wait
echo "The list: $thelist"

This obviously does not work as it should, because the threads are accessing the same variable - how should it be done properly

3 Answers 3

3

Bash does not support threads. Only subprocesses. And it is impossible to change a variable of parent process in a subprocess.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, then call a subprocess. So what would be the possible solution here? Use a tmp file to write the data into?
2

You might use a shared storage that handle concurrent updates, like a database.

Here is an example based on sqlite3:

function create_table
{
  sqlite3 thelist <<-%
  drop table t;
  create table t(one varchar(255));
  %
}

function add_to_list
{
  sqlite3 thelist <<-%
  .timeout 60000
  insert into t values('$$');
  %
}

function dump_list
{
  sqlite3 thelist <<-%
  select * from t;
  %
}

create_table
for i in $(seq 1 100); do
    add_to_list&
done

wait
thelist="$(dump_list)"
echo "The list: $thelist"

2 Comments

If I copy this to a test.sh script and execute with bash... bash -x test.sh I get syntax errors: test.sh: line 31: warning: here-document at line 3 delimited by end-of-file (wanted `%') test.sh: line 32: syntax error: unexpected end of file
@MikeSamaras Indeed. The issue is indentation should be done with tabs but copy/paste replaces tabs by spaces. Replace the leading double spaces by tabs and the script should run fine.
1

It seems to me that you're conflating threading and subprocessing semantics, especially wanting a variable to be updated.

You could use a named pipe like to communicate between the processes.

 $ mkfifo mypipe 


 $ cat < mypipe


 $ seq 1 10 > mypipe

This makes cat print the sequence.

bash-3.2$ cat always.sh

while : ; do
    cat < mypipe
done

bash-3.2$ seq 1 100  > mypipe & seq 100 200  > mypipe & seq 200 300 > mypipe & 

Creates out from always.sh 1 to 300 in order.

I'm unsure whether multiple processes writing to the same named pipe are synchronised safely.

Comments

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.