简体   繁体   中英

Is it allowed to use the same static void function to use multiple threads in c?

I think that the question is pretty self-explanatory, however here is an example of what I am referring to. say we have

static void *foo(void * bar) {

    //some random function/method/calculation/data manipulation.

}

is it safe/possible to create multiple threads and use that same function? I have a very lengthy file (approaching 1000 lines) Its starting to get lengthy to scroll up and down. long story short I can't afford errors or unintended functioning. Or would my better bet be to simply create another C file? my mutexing and everything is solid. so I'm not too worried.

int main() {
Is something like this feasable?: 

    pthread_t A1, A2;
    pthread_creat(&A1, NULL, foo, &foobar);
    pthread_create(&A2, NULL, foo, &foobar);
    
    pthread_join(A1, NULL);
    pthread_join(A2, NULL);
}

if i choose to head into this route any advice/precautions?

Code is constant in C, so there is no problem for multiple threads to use the same functions. What matters is the use of data by these functions: any access to shared modifiable data must be protected.

Note that some functions such as strtok() store their context in hidden static data and thus may not be thread safe.

In your example you pass the address of the same foobar object. Unless this object is constant throughout the lifetime of both threads, there would be concurrent access to shared modifiable data which would require special handling with locks or other forms of synchronisation.

A few thousand lines is not a lot of data, a single thread is a much simpler approach to your problem. Unless the processing of this data is very CPU intensive, multiple threads will create more problems for little benefit.

Proper thread programming is non-trivial to say the least. The answer to your question is yes, it is possible to pass the same function to different threads executing in parallel, but the devil is in the detail of how you deal with accessing shared data from those threads. Such a discussion far exceeds what can be explained in an answer. Without any information as to what data manipulation is performed, no clue can even be given as to how or even what to do.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM