0

i use multi thread to update each item(string) of global vector each thread update item(string) with different index i think is a good way to avoid updating same data but i still get core, i do not know why

extern vector<string> gTestVec; #define NUM 10 void * worker(void * args) { thread_data * p = (thread_data *)args; int i = p->thread_id; for (int j=0; j<100; j++) { gTestVec[i] += "a"; } return NULL; } void do_complete_stage_test::excute() { int i = 0; pthread_t thd[NUM]; thread_data data[NUM]; for (i=0; i<NUM; i++) { gTestVec.push_back(format("%d", i)); data[i].thread_id = i; if (0 != pthread_create(&(thd[i]), NULL, &worker, (void *)&data[i])) { printf("pthread_create failed"); } } for (int i=0; i<NUM; i++) { if (0 != pthread_join(thd[i], NULL)) { printf("pthread_join failed"); } } } 

when i run the code,sometimes get coredump

Starting program: /data/settle_script/isp_tran_collect/bin/isp_tran_collect -p 2134234 [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib64/libthread_db.so.1". [New Thread 0x7ffff2623700 (LWP 6316)] [New Thread 0x7fffefb0e700 (LWP 6317)] [New Thread 0x7fffef30d700 (LWP 6318)] Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0x7fffef30d700 (LWP 6318)] 0x00007ffff6787d67 in ?? () from /lib64/libstdc++.so.6 (gdb) bt #0 0x00007ffff6787d67 in ?? () from /lib64/libstdc++.so.6 #1 0x00007ffff678899b in std::string::reserve(unsigned long) () from /lib64/libstdc++.so.6 #2 0x00007ffff6788bbf in std::string::append(char const*, unsigned long) () from /lib64/libstdc++.so.6 #3 0x000000000044babe in append (__s=0x880492 "a", this=<optimized out>) at /usr/include/c++/4.8.2/bits/basic_string.h:1009 #4 operator+= (__s=0x880492 "a", this=<optimized out>) at /usr/include/c++/4.8.2/bits/basic_string.h:942 #5 worker (args=<optimized out>) at ../src/do_complete_stage_test.cpp:21 #6 0x00007ffff7bc6e25 in start_thread () from /lib64/libpthread.so.0 #7 0x00007ffff5ee635d in clone () from /lib64/libc.so.6 

thanks for your help!!!

1
  • 1
    Why use pthread instead of std::thread? With std::thread you could have a thread logic function with signature void worker(std::string& arg) (std::thread thd[NUM]; for (size_t i = 0; i != NUM; ++i){ ... thd[i] = std::thread(worker, std::reference_wrapper(gTestVec[i])); }) Commented Jun 6, 2022 at 8:09

1 Answer 1

3

You are potentially changing the capacity of the vector after you already started some threads.

The easiest way to prevent the vector from re-allocating and moving its contents is to reserve the amount of space before you start the first worker thread.

So call

gTestVec.reserve(NUM); 

Before your loop.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.