Happy
Happy

Reputation: 1

Multiple threads causing more CPU usage

For the code below my cpu usage is 97%. I am running c code on Ubuntu.

#include <stdio.h>
#include<pthread.h>
void *s_thread(void *x)
{
        printf("I am in first thread\n");
} 
void *f_thread(void *x)    
{
        printf("I am in second thread\n");
}

int main()
{
        printf("I am in main\n");
        pthread_t fth;
        int ret;
        ret = pthread_create( &fth,NULL,f_thread,NULL);
        ret = pthread_create( &sth,NULL,s_thread,NULL); 
        while(1);
        return 0;
}        

This simple code is giving me more cpu usage than running only one thread.

Upvotes: 0

Views: 1545

Answers (3)

Bo Morgan
Bo Morgan

Reputation: 11

Put a sleep command into your loop. For example, the following "sleep" command sleeps for one second:

while(1) {
  sleep(1);
}

There are other commands that sleep for less time, such as "usleep" provided by unistd.h, which sleeps for a given number of microseconds:

while(1) {
  usleep(1000);
}

Upvotes: 1

Lunar Mushrooms
Lunar Mushrooms

Reputation: 8918

In linux there are 3 threads :

  • 1 - main thread in which your main() is executing
  • 2 - f_thread
  • 3 - s_thread

The main thread waits on a while(1) loop, which is causing heavy resource usage. You should not use while(1), instead use pthread_join (http://www.manpagez.com/man/3/pthread_join/) .

With pthread_join, your main thread will sleep until other two threads are finished. Thus there won't be unnecessary resource usage.

Upvotes: 4

Munipratap
Munipratap

Reputation: 529

int main()
{
    printf("I am in main\n");

    pthread_t fth,sth;
    int ret;

    ret = pthread_create( &fth,NULL,f_thread,NULL);
    ret = pthread_create( &sth,NULL,s_thread,NULL); 

    pthread_join(&fth,NULL);
    pthread_join(&sth,NULL);

    return 0;
}

while(1) uses more CPU cycles, so use pthread_join and join the process so that main thread waits for child threads to complete.

Upvotes: 6

Related Questions