user114518
user114518

Reputation:

(C++) How can I suspend the main thread, then resume in it another thread?

I'm not working on Window's first off. I tried the techniques described here: to no avail.

Basically, I'm building a webcrawler that needs to suspend the main thread right before it outputs the results. The main thread needs to resume when my last pthread dies. I know the point when my last pthread dies, I just don't know how to suspend or resume the main thread.

Any help is greatly appreciated!

EDIT:

So, probably only one worker thread will exist at the point I want to suspend/resume main. I'm doing it in the constructor, and threads spawn as I gather more links.

Upvotes: 4

Views: 1451

Answers (3)

NFRCR
NFRCR

Reputation: 5580

The main thread is usually the thread from where you control other threads. If you need to wait until all the other threads are done why don't you monitor them from the main thread. Creating another thread to control the main thread seems like a design flaw.

Upvotes: 0

Bob Cross
Bob Cross

Reputation: 22312

It sounds like a basic fork-join model would work for you:

A thread join is a protocol to allow the programmer to collect all relevant threads at a logical synchronization point. For example, in fork-join parallelism, threads are spawned to tackle parallel tasks and then join back up to the main thread after completing their respective tasks (thus performing an implicit barrier at the join point). Note that a thread that executes a join has terminated execution of their respective thread function.

From an example later in the same document:

int main(int argc, char **argv) {  
    pthread_t thr[NUM_THREADS];  
    int i, rc;  /* create a thread_data_t argument array */  
    thread_data_t thr_data[NUM_THREADS];   /* create threads */  
    for (i = 0; i < NUM_THREADS; ++i) {    
        thr_data[i].tid = i;    
        if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) {      
            fprintf(stderr, "error: pthread_create, rc: %d\n", rc);      
            return EXIT_FAILURE;    
        }  
    }  

    /* block until all threads complete */  
    for (i = 0; i < NUM_THREADS; ++i) {    
        pthread_join(thr[i], NULL);  
    }   

    return EXIT_SUCCESS;
} 

Upvotes: 2

NPE
NPE

Reputation: 500883

In the main thread, call pthread_join() on each of the worker threads.

Upvotes: 6

Related Questions