快速锁(fastlock)
SylixOS 系统针对 POSIX 条件变量、POSIX 互斥信号量、POSIX 读写锁、POSIX 信号量设计了一种快速模式,称为 fastlock。
fastlock 模式相较于常规模式,在性能表现上有显著提升,尤其适用于那些对时间要求极为苛刻的场景,因而在此类情况下可优先考虑采用此机制进行并发控制。
SylixOS 内核编译完之后,会生成一个 fastlock 动态库,用户在开发应用程序的时候,链接该动态库,系统就会优先使用 fastlock 模式。在使用方式上,fastlock 模式与常规模式用法完全一致。
使用上文中 POSIX 互斥信号量的程序,链接 fastlock 动态库,使用 POSIX 互斥信号量的 fastlock 模式。
#include <stdio.h>
#include <pthread.h>
static pthread_mutex_t lock;
static int count = 0;
static void *thread_a (void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
count++;
printf("thread_a(): count = %d\n", count);
pthread_mutex_unlock(&lock);
usleep(500 * 1000);
}
return (NULL);
}
static void *thread_b (void *arg)
{
while (1) {
pthread_mutex_lock(&lock);
count++;
printf("thread_b(): count = %d\n", count);
pthread_mutex_unlock(&lock);
usleep(500 * 1000);
}
return (NULL);
}
int main (int argc, char *argv[])
{
pthread_mutexattr_t mutexattr;
pthread_t threada_tid;
pthread_t threadb_tid;
int ret;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_NORMAL);
pthread_mutexattr_setprotocol(&mutexattr, PTHREAD_PRIO_INHERIT);
ret = pthread_mutex_init(&lock, &mutexattr);
if (ret != 0) {
fprintf(stderr, "mutex create failed.\n");
return (-1);
}
pthread_mutexattr_destroy(&mutexattr);
ret = pthread_create(&threada_tid, NULL, thread_a, NULL);
if (ret != 0) {
fprintf(stderr, "pthread create failed.\n");
return (-1);
}
ret = pthread_create(&threadb_tid, NULL, thread_b, NULL);
if (ret != 0) {
fprintf(stderr, "pthread create failed.\n");
return (-1);
}
pthread_join(threada_tid, NULL);
pthread_join(threadb_tid, NULL);
pthread_mutex_destroy(&lock);
return (0);
}
链接 fastlock 动态库:
#*********************************************************************************************************
# Depend library (eg. LOCAL_DEPEND_LIB := -la LOCAL_DEPEND_LIB_PATH := -L"Your library search path")
#*********************************************************************************************************
LOCAL_DEPEND_LIB := \
-lfastlock
LOCAL_DEPEND_LIB_PATH :=
在 SylixOS Shell 下运行程序:
# ./POSIX_Mutex_Semaphore
thread_a(): count = 1
thread_b(): count = 2
thread_a(): count = 3
thread_b(): count = 4
thread_a(): count = 5
thread_b(): count = 6
......
# ts
NAME TID PID PRI STAT LOCK SAFE DELAY PAGEFAILS FPU CPU
--------------------- ------- ----- --- ---- ---- ---- ---------- --------- --- ---
POSIX_Mutex_Semaphore 4010078 37 200 JOIN 0 0 1 USE 0
pthread 4010079 37 200 SLP 0 268 0 0
pthread 401007a 37 200 SLP 0 268 0 0