我想用信号量同步10个线程,这样两个连续线程的执行之间会有一些延迟。因此,为了提供2秒的延迟(在这种情况下),我正在使用计时器。
//Import
#define _POSIX_C_SOURCE 199309
#include <sched.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syscall.h>
#define NUM_THREADS 10
#define CLOCKID CLOCK_REALTIME
#define SIG SIGUSR1
int ret;
timer_t timerid;
sem_t sem;
sem_t mute;
struct sigevent sev;
struct itimerspec its;
long long freq_nanosecs;
sigset_t mask;
struct sigaction sa;
pthread_t tid[NUM_THREADS];
static void handler(int sig, siginfo_t *si, void *uc)
{
if(si->si_value.sival_ptr != &timerid){
printf("Stray signal\n");
}
sem_post(&sem);
}
void *threadA(void *data_)
{
int i = 0, s,n;
int turn = (intptr_t)data_;
int sid = syscall(SYS_gettid);
FILE *fp;
fp=fopen("ipc.out","a");
fprintf(fp,"thread_%d %d\n",turn,sid);
fclose(fp);
while(1)
{
sem_wait(&sem);
printf("Thread #-> %d\n",turn);
sem_wait(&mute);
for (int i = 0; i < 100000; ++i)
{
/* some work */
}
its.it_value.tv_sec = 2;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
ret = timer_settime(timerid, 0, &its, NULL);
if ( ret < 0 )
perror("timer_settime");
sem_post(&mute);
// Timer's code ends
}
}
int main(int argc, char *argv[])
{
int data = 0;
int err,i;
sem_init(&sem, 0, 1);
sem_init(&mute, 0, 1);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
sigaction(SIG, &sa, NULL);
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
ret = timer_create(CLOCKID, &sev, &timerid);
if ( ret < 0 )
perror("timer_create");
while(data < NUM_THREADS)
{
//create our threads
err = pthread_create(&tid[data], NULL, threadA, (void *)(intptr_t)data);
if(err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
data++;
}
pthread_exit(NULL);
}
所以,如果线程#1有了CPU,那么它应该在执行所有其他线程后再次获得CPU。 但就我而言,线程#0将在每个线程之后出现。 输出:
root@localhost:~/Desktop/C_files# ./a.out
Thread # -> 2
Thread # -> 0
Thread # -> 3
Thread # -> 0
Thread # -> 7
Thread # -> 0
Thread # -> 4
Thread # -> 0
Thread # -> 5
Thread # -> 0
Thread # -> 8
Thread # -> 0
Thread # -> 1
Thread # -> 0
Thread # -> 6
Thread # -> 0
Thread # -> 9
Thread # -> 0
Thread # -> 2
Thread # -> 0
为什么线程#0频繁出现(在每个线程之间)?我希望一个线程只有在所有其他线程都运行一次时才开始第二次执行。