我不理解为什么如果我使用
while (tab[i+1] == 0)
{
i+=1;
}
我的程序卡住了,但是如果我使用
while (tab[++i] == 0);
它按照预期的方式执行。我错过了什么吗?
完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <limits.h>
#define SIZE 100
typedef struct
{
unsigned int prime;
unsigned int size;
unsigned int *tab;
} shared_data;
void *sieve(void *);
sem_t mutex;
int main()
{
pthread_t tid;
unsigned int tab[SIZE];
sem_init(&mutex, 0, 0);
for (unsigned int i = 0; i < SIZE; i++)
{
tab[i] = i;
}
unsigned int i = 2; //index startowy
shared_data shared = {i, SIZE, tab};
while (i < SIZE)
{
shared.prime = tab[i];
pthread_create(&tid, NULL, sieve, &shared);
sem_wait(&mutex);
while (tab[++i] == 0);
}
pthread_join(tid, NULL); // czekaj az ostatni watek zakonczy dzialanie
sem_destroy(&mutex);
printf("Liczby pierwsze:\n");
for (unsigned int i = 0; i < SIZE; i++)
if (tab[i]) //pomin 0 przy wyswietlaniu
printf("%d | ", tab[i]);
printf("\n");
return 0;
}
void *sieve(void *arg_p)
{
shared_data arg = *(shared_data *)arg_p;
shared_data io = arg;
int unlock_thread = 1;
for (unsigned int i = io.prime + 1; i < io.size; i++)
{
if (io.tab[i] % io.prime == 0)
io.tab[i] = 0;
else if (unlock_thread)
{
sem_post(&mutex);
unlock_thread = 0;
}
}
if (unlock_thread)
sem_post(&mutex);
return NULL;
}