【发布时间】:2016-02-17 03:08:49
【问题描述】:
我是 linux 内核开发的新手。我试图学习线程创建和同步。我的最终目标是创建两个线程,这两个线程使用由信号量保护的共享资源。
代码是
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<semaphore.h>
sem_t sema_obj;
pthread_t tid[2];
int shared_val = 0;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
for(i=0;i<5;i++){
printf("\n going to wait %x\n",(unsigned int)id);
sem_wait(&sema_obj);
shared_val++;
sleep(1);
printf("\n %d The value of shared_val is %d in thread %x \n",(int)i, shared_val, (unsigned int)id);
sem_post(&sema_obj);
printf("\n gave up sem %x\n",(unsigned int)id);
}
for(i=0; i<(0xFFFFFFFF);i++);
return NULL;
}
int main(void)
{
int i = 0;
int err;
sem_init(&sema_obj, 0, 1);
while(i < 2)
{
pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
param.sched_priority = 50;
pthread_attr_setschedparam(&attr, ¶m);
//sched_setscheduler(current, SCHED_FIFO, ¶m);
err = pthread_create(&(tid[i]), &attr, &doSomeThing, NULL);
//err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully 0x%X \n",(unsigned int)tid[i]);
i++;
}
enter code here
sleep(60);
return 0;
}
我正在编译它
gcc -o threads_op -pthread -lrt threads.c
运行代码后,我看到:
Thread created successfully 0xB75CBB40
going to wait b75cbb40
Thread created successfully 0xB6DCAB40
going to wait b6dcab40
0 The value of shared_val is 1 in thread b75cbb40
gave up sem b75cbb40
going to wait b75cbb40
1 The value of shared_val is 2 in thread b75cbb40
gave up sem b75cbb40
going to wait b75cbb40
2 The value of shared_val is 3 in thread b75cbb40
gave up sem b75cbb40
going to wait b75cbb40
3 The value of shared_val is 4 in thread b75cbb40
gave up sem b75cbb40
going to wait b75cbb40
4 The value of shared_val is 5 in thread b75cbb40
gave up sem b75cbb40
0 The value of shared_val is 6 in thread b6dcab40
gave up sem b6dcab40
going to wait b6dcab40
1 The value of shared_val is 7 in thread b6dcab40
gave up sem b6dcab40
going to wait b6dcab40
2 The value of shared_val is 8 in thread b6dcab40
gave up sem b6dcab40
going to wait b6dcab40
3 The value of shared_val is 9 in thread b6dcab40
gave up sem b6dcab40
going to wait b6dcab40
4 The value of shared_val is 10 in thread b6dcab40
gave up sem b6dcab40
此进程的 RTPRIO 为“-”, S 1000 4551 4338 - 00:00:00 线程操作
有以下问题,
1) 为什么线程不是实时的,并占据我设置的优先级?
2) 为什么信号量没有被两个线程交替锁定并更新共享变量?两个线程具有相同的优先级。
如果您知道了解linux内核主题的分步教程,请分享。
【问题讨论】:
-
为什么会提到 Bash?
-
你不应该对实时应用程序使用睡眠,因为它只是一个最小的时间保证,即你的线程将等待至少 1s ,然后你将拥有你的系统时间粒度。
-
睡眠唤醒对于实时线程来说会更准确,实际上。但是 sleep() 只有第二个粒度。
标签: linux scheduled-tasks scheduler