int pthread_spin_init(pthread_spinlock_t *lock, int pshared);
int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);
int pthread_spin_destroy(pthread_spinlock_t *lock);
#include #include #include #include static unsigned int num = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /*在sys/time.h中定义的*/ // typedef struct timeval // { // long tv_sec; //秒 // long tv_usec; //微秒 // }timeval; __int64_t get_current_timestamp() { struct timeval now = {0, 0}; gettimeofday(&now, NULL); return now.tv_sec * 1000 * 1000 + now.tv_usec; } void thread_proc() { for(int i = 0; i < 1000000; ++i) { pthread_mutex_lock(&mutex); ++num; pthread_mutex_unlock(&mutex); } } int main() { pthread_t t1, t2; __int64_t start = get_current_timestamp(); pthread_create(&t1, NULL, (void*)thread_proc, NULL); pthread_create(&t2, NULL, (void*)thread_proc, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("num:%d\n", num); __int64_t end = get_current_timestamp(); printf("cost:%ld\n", end - start); pthread_mutex_destroy(&mutex); return 0; }
#include #include #include #include static unsigned int num = 0; pthread_spinlock_t spin_lock; /*在sys/time.h中定义的*/ // typedef struct timeval // { // long tv_sec; //秒 // long tv_usec; //微秒 // }timeval; __int64_t get_current_timestamp() { struct timeval now = {0, 0}; gettimeofday(&now, NULL); return now.tv_sec * 1000 * 1000 + now.tv_usec; } void thread_proc() { for(int i = 0; i < 1000000; ++i) { pthread_spin_lock(&spin_lock); ++num; pthread_spin_unlock(&spin_lock); } } int main() { pthread_t t1, t2; pthread_spin_init(&spin_lock, PTHREAD_PROCESS_PRIVATE); __int64_t start = get_current_timestamp(); pthread_create(&t1, NULL, (void*)thread_proc, NULL); pthread_create(&t2, NULL, (void*)thread_proc, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("num:%d\n", num); __int64_t end = get_current_timestamp(); printf("cost:%ld\n", end - start); pthread_spin_destroy(&spin_lock); return 0; }
void thread_proc() { for(int i = 0; i < 1000000; ++i) { pthread_spin_lock(&spin_lock); for(int j = 0; j < 1000; ++j) { ++num; } pthread_spin_unlock(&spin_lock); } }
上一篇:二维码登录的原理
下一篇:Qt框架下实现商品库存管理系统