我们都知道,Write 方法不能保证从缓冲区中写入高字节。因此,使用原始 Write 方法将字节写入套接字的规范方法如下所示
//how many bytes we have written
written := 0
for written < len(msg){
//write the bytes from buffer that havent been witten yet
wr, err := conn.Write(msg[written:])
if err != nil{
return;
}
written += wr
}
Run Code Online (Sandbox Code Playgroud)
现在假设我不想使用如此低级的技术,并且想使用一个可以为我完成此操作的函数。我应该使用标准库中的哪个函数?
我正在编写一个程序,它计算数组中 0 到 100 万(不包括)之间整数的平方。我最多使用 8 个线程(包括)。
为了索引数组,我使用了一个原子整数。
我希望无论线程数如何,run 方法中的 for 循环体都会执行一百万次。
为了计算它被执行的次数,我使用了另一个原子整数。
static AtomicInteger cnt = new AtomicInteger(0);
static AtomicInteger ii = new AtomicInteger(0);
static long[] arr = new long[1_000_000];
public static class Worker extends Thread {
public static void main(String[] args) throws IOException, InterruptedException {
int maxThreads = Runtime.getRuntime().availableProcessors() * 2;
for (int n = 1; n <= maxThreads; n++) {
int numThreads = n;
Thread[] threads = new Thread[numThreads];
ii = new AtomicInteger(0);
for (int i = …Run Code Online (Sandbox Code Playgroud)