multi thread global class

I am making a multithread program using C++, GNU under Ubuntu.
There will be a global class object called server. server.processRequest(str) will be called by each thread. Question is, within the server.processRequest(), should I dynamically declare all the variables needed to be used? What I am concerning is, if two thread are calling server.processRequest() at the same time, are the variables used in server.processRequest() not thread-safe? the server object is global to all threads, dose that mean the methods of this object is also global to all threads, instead of that each thread will have a new copy of the global objects' method?
to answer that question, you have to decide how much sharing of variable str you want between threads

1. if there is none, you could make it local to each thread

2. if there is read-only sharing (like in your specific case, make those strings const), as long as you allocate all the variables before you spawn any threads, you will be thread-safe

btw, in threading, don't worry about copies of code - worry about variables and state

I recommend that you grab a copy of valgrind (in particular use drd, which has been around longer, or helgrind) to convince yourself that your multithreading code is ok:

http://valgrind.org/

sudo apt-get install valgrind

should work fine for you - gl
Last edited on
what abort there is read-write sharing?
for example:

following is a simplified demonstration of content of threads and global class object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Server
{
    ....
    ....
    process(char *request)
    {
           char *tmp=request;
           int a=strlen(request);
           ......

    }
}


Server server;

void threadEntry()
{
          .........
          server.process(request);
}

int main(){
         while(.......)
         {
              pthread_create(....threadEntry);
              ..............
         }
         ................

}



Is above code thread safe? if at any time, two threads are calling server.process() at the same time, will the content of the variable "int a" suffer race condition or other thread problems?
if the request on Line 20 is allocated on a per-thread basis (ie isolated from all other threads), you are ok because tmp on Line 7 is an automatic variable

if Line 7 were a static or some kind of global variable, you would be in trouble

now, if I recall correctly, strlen() is thread-safe so Line 8 is ok, but if you were using a non-threadsafe call here like some I/O calls or time(), you would also be in trouble without a mutex

edit: clarification on the I/O - suppose each thread were writing to a different file: that would be fine as there is no dependencies between them
Last edited on
thank you very much!!
Topic archived. No new replies allowed.