I have the following code:
somefunc(string s, semaphore* sem) {
//some functionality
sem->signal();
}
int main() {
int num = 0;
semaphore sem(0);
vector<string> arr;
for (string& s : arr) {
++num;
thread(somefunc, s, &sem).detach();
}
for (int i = 0; i < num; i++)
sem.wait();
}
I am getting SIGSEGV
errors inside std::string
allocation on the line where thread()
is. Is there something wrong with this code? semaphore
is a custom class that uses a mutex and a conditional variable.
It's hard to tell without seeing your real code, but my guess is that when the string reference s
is being copied inside thread
it is no longer valid because the main thread has already exited the scope containing arr
.
Running your code under valgrind or a similar memory checker should help diagnose the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.