Home > Software design >  Properly use an argv entry as a variable in another function
Properly use an argv entry as a variable in another function

Time:10-06

I am writing a program where I pass the first argument (argv[1]) which determines the amount of threads I want to use to run a function. I made a global variable called THREAD_COUNT, which is takes place in argv[1] and converts it to a integer with atoi().

I then want to use that thread_count variable to use as a divisor in a for loop which represent the amount of threads I want to use.

I can't seem to get this right, as my logic doesnt work and I get a floating point exception. Would I have to make a pointer out of something?

Go easy on me, I am a begginer programmer and I never used C before.

The code below is for 2 and 4 threads, just ignore the FUNCTION variable.

#include <"transact.h">
#include <pthread.h>


int balance = 100000000;
int THREAD_COUNT;
int FUNCTION;

void * process(void * arg) {

for(int i = 0; i < 100000000/THREAD_COUNT; i  ) {

int transaction = getTransaction(i);

balance = balance - 1;

printf("%d : %d\n", i, transaction);

      } 

}



int main(int argc, char * argv[]) {

int THREAD_COUNT = atoi(argv[1]);

int FUNCTION = atoi(argv[2]);


if (THREAD_COUNT == 2 && FUNCTION == 0) {

pthread_t thread1, thread2;

pthread_create(&thread1, NULL, process, NULL);

pthread_create(&thread2, NULL, process, NULL);

pthread_join(thread1, NULL);

pthread_join(thread2, NULL);

printf("Balance is: %d \n", balance);

}
else if (THREAD_COUNT == 4 && FUNCTION == 0){

pthread_t thread1, thread2, thread3, thread4;

pthread_create(&thread1, NULL, process, NULL);

pthread_create(&thread2, NULL, process, NULL);

pthread_create(&thread3, NULL, process, NULL);

pthread_create(&thread3, NULL, process, NULL);

pthread_join(thread1, NULL);

pthread_join(thread2, NULL);

pthread_join(thread3, NULL);

pthread_join(thread4, NULL);

}

else {

printf("Enter 2, 4, 8 \n ");

}

}

CodePudding user response:

You have both a global variable named THREAD_COUNT, with an undefined value, and then a local variable named THREAD_COUNT in your main function which shadows the global variable.

That means the global THREAD_COUNT never gets set, so you're probably dividing by 0.

You need to modify the beginning of your main function to look like:


int main(int argc, char * argv[]) {

    THREAD_COUNT = atoi(argv[1]);
    FUNCTION = atoi(argv[2])

    ...
}

By not re-declaring the variables, this sets the global vars, rather than setting a local variable of the same name.


Also note that with your current code, if you forget to pass cli arguments it will fail with a segmentation fault (because it will call atoi with a null value). You might want to protect against that.

  •  Tags:  
  • c
  • Related