This line quoted actually changes the string to a character "d" rather than deleting the line.
(echo "s/THREAD #2/d"; echo 'wq') | ex -s temp_file.txt
This will actually delete the line containing the first occurance of the string.
(echo "/THREAD #2/d"; echo 'wq') | ex -s temp_file.txt
However if another process has the file open (check with "fuser") then the edit could be failing.