#include<pthread.h>
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define ERROR_CREATE 1
#define ERROR_JOIN 2
// create the function to be executed as a thread
void *thread(void *ptr)
{
uintptr_t type = (uintptr_t) ptr; // thread number
srand(time(NULL) + getpid());
int wait = rand() % 10; // randomizes numbers from 0 to 10
sleep(wait); // waits in time intervals of seconds
printf("Thread - %ld waiting for %d seconds\n",type, wait);
return ptr; // returns the thread number
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Error with command line arguments");
}
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads]; // array of thread types
for (long i = 1; i <= num_threads; i++) {
if (pthread_create(&threads[i], NULL, thread, (void *)i) != 0)
// if there's an error creating thread
{
fprintf(stderr,"Error: could not create thread");
return ERROR_CREATE;
}
}
// terminate each thread assigned
for (int i = 1; i <= num_threads; i++) {
if (pthread_join(threads[i], NULL) != 0)
// if there's an error ending each thread
{
fprintf(stderr, "Error: could not terminate thread");
return ERROR_JOIN;
}
}
return 0;
}
Посеяв функцию rand, я все равно получаю одно и то же число. Я понимаю, что аппаратное обеспечение быстрое и поэтому получает тот же ответ, поскольку тактовая частота выше, чем заполнение функции rand. Кто-нибудь знает другой способ получить больше разнообразия от функции rand?
Это минимальный воспроизводимый пример? Похоже, что большая часть вашего кода не имеет ничего общего с генерацией случайных значений и может быть вырезана. Задавая вопрос, представьте, что вы просите занятого коллегу помочь вам. Потому что вы есть. Все, что вы можете сделать, чтобы облегчить мне вопрос, даст вам лучший ответ, и вы получите этот ответ быстрее.
getpid()
во всех темах одинаково. Используйте gettid()
, чтобы получить идентификатор темы.
Индексы @Alex Fridman в C для массивов начинаются с 0.
Также обратите внимание, что «rand() не гарантирует потокобезопасность».
ObDilbert: dilbert.com/strip/2001-10-25
argv[1]
не заполнен, в противном случае происходит ошибка сегментации.srand()
сбрасывает последовательность. Поскольку вы вызываете его несколько раз с одним и тем же значением, это не то, что вам нужно. Переместил main()
.threads
осуществляется за пределами границ в двух циклах.#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define ERROR_CREATE 1
#define ERROR_JOIN 2
// create the function to be executed as a thread
void *thread(void *ptr) {
uintptr_t type = (uintptr_t) ptr; // thread number
int wait = rand() % 10; // randomizes numbers from 0 to 10
sleep(wait); // waits in time intervals of seconds
printf("Thread - %ld waiting for %d seconds\n",type, wait);
return ptr; // returns the thread number
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Error with command line arguments\n");
return 1;
}
srand(time(NULL));
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads]; // array of thread types
for (long i = 0; i < num_threads; i++) {
if (pthread_create(&threads[i], NULL, thread, (void *)i) != 0)
// if there's an error creating thread
{
fprintf(stderr,"Error: could not create thread");
return ERROR_CREATE;
}
}
// terminate each thread assigned
for (int i = 0; i < num_threads; i++) {
if (pthread_join(threads[i], NULL) != 0)
// if there's an error ending each thread
{
fprintf(stderr, "Error: could not terminate thread");
return ERROR_JOIN;
}
}
}
И вот пара пробных прогонов:
$ ./a.out 2
Thread - 1 waiting for 3 seconds
Thread - 2 waiting for 7 seconds
$ ./a.out 2
Thread - 1 waiting for 3 seconds
Thread - 2 waiting for 6 seconds
Не звоните srand() в каждой теме. Назовите это один раз в main().