我是多线程的新手,而且总体来说并不是 C 语言中最好的,所以对我来说就这样了。
我有一个 for 循环,它创建了许多线程,我将参数传递给这些线程:
for(int i = 0; i < NO_OF_THREADS; i++) {
int ordered_product = (rand() % NO_OF_PRODUCTS);
int ordered_quantity = (rand() % 10) + 1;
int customer = (rand() % NO_OF_CUSTOMERS);
printf("%d %d %d\n", customer+1, ordered_quantity, ordered_product+1);
ThreadArgs myargs = {customer, ordered_product, ordered_quantity};
int rc = pthread_create(&mythreads[i], NULL, thread_function, &myargs);
if(rc != 0) {
perror("Pthread create");
exit(1);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个函数“thread_function”,它是这样写的:
void* thread_function(void* arg) {
ThreadArgs* args = (ThreadArgs*) arg;
ThreadArgs myargs = *args;
int customer_id = …Run Code Online (Sandbox Code Playgroud)