正确使用 argv 条目作为另一个函数中的变量

AMC*_*e96 1 c

我正在编写一个程序,其中传递第一个参数 (argv[1]),该参数确定我想要用来运行函数的线程数量。我创建了一个名为 THREAD_COUNT 的全局变量,它发生在 argv[1] 中,并使用 atoi() 将其转换为整数。

然后,我想使用 thread_count 变量作为 for 循环中的除数,表示我想要使用的线程数量。

我似乎无法做到这一点,因为我的逻辑不起作用并且我得到了浮点异常。我必须用一些东西来做一个指针吗?

别介意我,我是一名初级程序员,以前从未使用过 C。

下面的代码适用于 2 和 4 线程,只需忽略该FUNCTION变量。

#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 ");

}

}
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 5

您有一个名为 的全局变量THREAD_COUNT,其值未定义,还有一个在函数中命名的局部变量,该变量会隐藏该全局变量。THREAD_COUNTmain

这意味着全局THREAD_COUNT永远不会被设置,所以你可能会除以 0。

您需要将函数的开头修改main为:


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

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

通过不重新声明变量,这将设置全局变量,而不是设置同名的局部变量。


另请注意,对于您当前的代码,如果您忘记传递 cli 参数,它将因分段错误而失败(因为它将atoi使用空值进行调用)。您可能想防止这种情况发生。