gpt4 book ai didi

java - Java 锁是 C 中的 PThread_Mutex 吗?

转载 作者:行者123 更新时间:2023-12-01 16:54:37 25 4
gpt4 key购买 nike

我用 C 和 Java 编写了完全相同的程序,其中两个线程递增全局计数器。为了确保 C 中计数器访问的排他性,使用了 pthread_mutex_t,而在 Java 中则使用 synchronized(lock):

C 版本:

  1 #include <stdio.h>
2 #include <pthread.h>
3
4 static volatile int global;
5 static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
6
7 static void *run(void *arg) {
8 int nLoop = *((int *) arg);
9 int localValue;
10
11
12
13
14
15 for (int j = 0; j < nLoop; j++) {
16 pthread_mutex_lock(&mtx);
17 localValue = global;
18 localValue = localValue + 1;
19 global = localValue;
20 pthread_mutex_unlock(&mtx);
21 }
22 return NULL;
23 }
24
25 int main() {
26 pthread_t t1, t2;
27 int nLoop = 100000;
28
29 int i = 0;
30 while (i<10) {
31 global = 0;
32 pthread_create(&t1, NULL, run, &nLoop);
33 pthread_create(&t2, NULL, run, &nLoop);
34
35 pthread_join(t1, NULL); pthread_join(t2, NULL);
36 printf("global: %d\n", global);
37 i++;
38 }
39 return 0;
40 }

Java 版本:

  1 public class ThreadIncr {
2
3
4 static int global;
5 private final static Object lock = new Object();
6
7 static class R implements Runnable {
8 int nLoop;
9 int localValue;
10
11 public R(int nLoop) { this.nLoop = nLoop; }
12
13 @Override
14 public void run() {
15 for(int j = 0; j<this.nLoop; j++) {
16 synchronized(lock) {
17 localValue = global;
18 localValue = localValue + 1;
19 global = localValue;
20 }
21 }
22 }
23 }
24
25 public static void main(String[] args) throws InterruptedException {
26 Thread t1, t2;
27 int nLoop = 100000;
28
29 int i = 0;
30 while (i < 10) {
31 global = 0;
32 t1 = new Thread(new R(nLoop));
33 t2 = new Thread(new R(nLoop));
34 t1.start(); t2.start();
35 t1.join(); t2.join();
36 System.out.println("global: " + global);
37 i++;
38 }
39 }
40 }

那么基本上Java的锁就是C中的互斥锁?

最佳答案

在Java中“synchronized(lock)”意味着使用所谓的监视器锁。该监视器锁提供互斥( link )。因此,它提供了与 C 中互斥锁相同的功能。

关于java - Java 锁是 C 中的 PThread_Mutex 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61611598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com