初学多线程,写出了如下程序
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <pthread.h>
#include <semaphore.h>
#define num 1
sem_t p[num];
int finished1[num];
// int t= 0;
void *foo(void *args)
{
int* a = (int *)args;
printf("the number is :%d\n", *a);
sem_wait(&p[*a]);
printf("--finish: %d\n", finished1[*a]);
int s = 1;
for (int i = 1; i <= 1000; i ++)
s = i * (i + 1) % 43;
finished1[*a] = 1;
printf("finish: %d\n", finished1[*a]);
pthread_exit(0);
}
int main()
{
int t= 0;
for (int i = 0; i < num; i ++) sem_init(&p[i], 0, 0);
pthread_t th[1001];
for (int i = 0; i < 1; i ++)
{
pthread_create(&th[i], NULL, foo, (void *)&t);
}
for (int i = 0; i < num; i ++)
{
sem_post(&p[i]);
while(finished1[i] == 0)
{
};
finished1[i] = 0;
printf("--%d--\n", i);
}
return 0;
}
发现如果用O1/O2优化的话,程序不能终止
不优化程序能正常运行
目前太菜了,找不出问题,在此记录…