This commit is contained in:
p-w-rs
2022-09-22 14:34:03 -05:00
parent c506ca8b3b
commit ed1585d26b
32 changed files with 253 additions and 52 deletions

View File

@@ -16,8 +16,10 @@
// Returns 1 if prime, 0 if not prime
int is_prime(int v)
{
for(int i = 2; i < v; i++) {
if(v % i == 0) {
for (int i = 2; i < v; i++)
{
if (v % i == 0)
{
return 0;
}
}
@@ -29,13 +31,16 @@ int is_prime(int v)
// Modifies the input parameter by dereferencing the pointer
//
// NOTE: that parameters and return value are pointers
void* thread_routine(void* args)
void *thread_routine(void *args)
{
int* val = (int*)args;
if(is_prime(*val)) {
int *val = (int *)args;
if (is_prime(*val))
{
printf("THREAD %lu FOUND that %d is prime %p\n", pthread_self(), *val, val);
*val = 1;
} else {
}
else
{
printf("THREAD %lu FOUND that %d is not prime %p\n", pthread_self(), *val, val);
*val = 0;
}
@@ -48,18 +53,21 @@ int main()
// Create 10 threads
pthread_t thr[10];
for(int i = 0; i < 10; i++) {
for (int i = 0; i < 10; i++)
{
// NOTE: there is a single memory location for val which is passed to all threads
val = i + 2;
if(pthread_create(&thr[i], NULL, thread_routine, (void*)&val) == -1) {
if (pthread_create(&thr[i], NULL, thread_routine, (void *)&val) == -1)
{
printf("COULD NOT CREATE A THREAD\n");
exit(EXIT_FAILURE);
}
}
// Wait for threads to finish
for(int i = 0; i < 10; i++) {
for (int i = 0; i < 10; i++)
{
pthread_join(thr[i], NULL);
}