前置内容:并发锁与线程池(一)
1.互斥锁的实现
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define THREAD_COUNT 10
pthread_mutex_t mutex;
void *thread_callback(void *arg) {
int *pcount = (int *)arg;
int i = 0;
while (i ++ < 100000) {
pthread_mutex_lock(&mutex);
(*pcount) ++;
pthread_mutex_unlock(&mutex); //互斥锁
usleep(1);
}
}
``int main () {
pthread_t threadid[THREAD_COUNT] = {0};
pthread_mutex_init(&mutex, NULL); //初始化互斥锁
int i = 0;
int count = 0;
for (i = 0;i < THREAD_COUNT;i ++) {
pthread_create(&threadid[i], NULL, thread_callback, &count);
} //创建线程
for (i = 0;i < 100;i ++) {
printf("count : %d\n", count);
sleep(1);
}
}
2.自旋锁的实现:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define THREAD_COUNT 10
pthread_spinlock_t spinlock;
void *thread_callback(void *arg) {
int *pcount = (int *)arg;
int i = 0;
while (i ++ < 100000) {
pthread_spin_lock(&spinlock);
(*pcount) ++; //
pthread_spin_unlock(&spinlock);
usleep(1);
}
}
int main () {
pthread_t threadid[THREAD_COUNT] = {0};
pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED); //初始化自旋锁
int i = 0;
int count = 0;
for (i = 0;i < THREAD_COUNT;i ++) {
pthread_create(&threadid[i], NULL, thread_callback, &count);
} //创建线程
for (i = 0;i < 100;i ++) {
printf("count : %d\n", count);
sleep(1);
}
}
3.原子操作的实现:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define THREAD_COUNT 10
int inc(int *value, int add) {
int old;
__asm__ volatile(
"lock; xaddl %2, %1;"
: "=a" (old)
: "m" (*value), "a"(add)
: "cc", "memory"
);
return old;
} //原子操作
void *thread_callback(void *arg) {
int *pcount = (int *)arg;
int i = 0;
while (i ++ < 100000) {
inc(pcount, 1);
#endif
usleep(1);
}
}
int main () {
pthread_t threadid[THREAD_COUNT] = {0};
int i = 0;
int count = 0;
for (i = 0;i < THREAD_COUNT;i ++) {
pthread_create(&threadid[i], NULL, thread_callback, &count);
} //创建线程
for (i = 0;i < 100;i ++) {
printf("count : %d\n", count);
sleep(1);
}
}
标签:count,COUNT,int,++,并发,线程,pthread,include
From: https://blog.csdn.net/m0_74973115/article/details/137154015