即使在应用未经检查后,算术运算也会导致溢出
Arithmetic operation resulted in an overflow even after applying unchecked
为什么即使我在表达式上应用 unchecked
运算符也会出现溢出异常?
return GetCharStream().AsParallel().Aggregate<char, int[], int[]>(() => new int[26],
(ca, c) =>
{
int i = char.ToUpper(c) - 'A';
if (i > -1 && i < 26)
unchecked { ca[i]++; }
return ca;
},
(ma, la) =>
{
return ma.Zip(la, (t1, t2) => { return unchecked(t1 + t2); }).ToArray();
},
fResult => fResult);
Update:
即使我完全删除代码中的所有算术运算,我仍然得到 arithmetic overflow exception
:-
double[] CountAggregateParallel()
{
//196386
return GetCharStream().AsParallel().Aggregate(() => (new double[26]),
LocalAccumulator,
FinalAccumulator,
fResult => fResult);
}
private static double[] FinalAccumulator(double[] ma, double[] la)
{
return ma;
}
private static double[] LocalAccumulator(double[] ca, char c)
{
return ca;
}
IEnumerable<char> GetCharStream()
{
int i = 0;
while (i < 200_000)
{
foreach (char c in str)
{
yield return c;
}
Console.WriteLine($"{i+1} iteration of str complete");
i++;
}
}
str
变量的值:
string str = @"This chapter explains how unfavorable association is a threat to one’s position in devotional service and how by associating with saintly persons one can attain the highest platform of devotion.
The jīva who has received a human body, which is in itself most conducive toward achieving the Supreme Personality of Godhead, and who has situated himself in the duties of devotional service to the Lord becomes capable of realizing Him, the very identity of spiritual bliss. Such a person, fully dedicated to the Supreme Personality, is liberated from the influence of Māyā; even while continuing to reside in this world created by illusion he is totally untouched by it. Those souls, on the other hand, who are bound up by Māyā are devoted only to their bellies and genitals. They are impure, and by associating with them one will fall down into the dark pit of ignorance.
The emperor Purūravā, who was bewildered by the association of the heavenly lady Urvaśī, later became renounced after being separated from her. He thus sang a song expressing his contempt for womanly connection. He described that persons who are attached to the body of a woman (or a man) — which is simply a mass of skin, meat, blood, sinew, brain tissue, marrow and bones — are not much different from worms. What is the worth of the education, austerity, renunciation, reception of the Vedas, solitary living and silence of one whose mind becomes stolen away by the body of a woman? Learned men should distrust their six mental enemies, headed by lust, and thus avoid associating with women or with men who are controlled by women. After declaring these facts, King Purūravā, now freed from the illusion of material existence, attained realization of the Supreme Lord in His form as the indwelling Supersoul.
In conclusion, one who is intelligent should give up bad association and let himself become attracted to the company of saintly persons. By their transcendental instructions, the saintly devotees of the Lord can break the false attachments of one’s mind. Real saints are always liberated and devoted to the Supreme Personality of Godhead. In their association there are constant discussions about the Supreme Lord, by serving whom the spirit soul completely eradicates his material sins and obtains pure devotional service. And when one gains the devotional service of the Supreme Personality of Godhead, who is the original ocean of unlimited perfect qualities, what else remains to be gained?
Text 1: The Supreme Personality of Godhead said: Having achieved this human form of life, which affords one the opportunity to realize Me, and being situated in My devotional service, one can achieve Me, the reservoir of all pleasure and the Supreme Soul of all existence, residing within the heart of every living being.
Text 2: A person fixed in transcendental knowledge is freed from conditioned life by giving up his false identification with the products of the material modes of nature. Seeing these products as simply illusion, he avoids entanglement with the modes of nature, although constantly among them. Because the modes of nature and their products are simply not real, he does not accept them.
Text 3: One should never associate with materialists, those dedicated to gratifying their genitals and bellies. By following them one falls into the deepest pit of darkness, just like a blind man who follows another blind man.
Text 4: The following song was sung by the famous emperor Purūravā. When deprived of his wife, Urvaśī, he was at first bewildered, but by controlling his lamentation he began to feel detachment.
Text 5: When she was leaving him, even though he was naked he ran after her just like a madman and called out in great distress, “O my wife, O terrible lady! Please stop!”
Text 6: Although for many years Purūravā had enjoyed sex pleasure in the evening hours, still he was not satisfied by such insignificant enjoyment. His mind was so attracted to Urvaśī that he did not notice how the nights were coming and going.
Text 7: King Aila said: Alas, just see the extent of my delusion! This goddess was embracing me and held my neck in her grip. My heart was so polluted by lust that I had no idea how my life was passing.
Text 8: That lady cheated me so much that I did not even see the rising or setting of the sun. Alas, for so many years I passed my days in vain!
Text 9: Alas, although I am supposed to be a mighty emperor, the crown jewel of all kings on this earth, just see how my bewilderment has rendered me a toy animal in the hands of women!
Text 10: Although I was a powerful lord with great opulence, that woman gave me up as if I were no more than an insignificant blade of grass. And still, naked and without shame, I followed her, crying out to her like a madman.
Text 11: Where are my so-called great influence, power and sovereignty? Just like an ass being kicked in the face by his she-ass, I ran after that woman, who had already given me up.
Text 12: What is the use of a big education or the practice of austerities and renunciation, and what is the use of studying religious scriptures, of living in solitude and silence, if, after all that, one’s mind is stolen by a woman?
Text 13: To hell with me! I am such a fool that I didn’t even know what was good for me, although I arrogantly thought I was highly intelligent. Although I achieved the exalted position of a lord, I allowed myself to be conquered by women as if I were a bullock or a jackass.
Text 14: Even after I had served the so-called nectar of the lips of Urvaśī for many years, my lusty desires kept rising again and again within my heart and were never satisfied, just like a fire that can never be extinguished by the oblations of ghee poured into its flames.
Text 15: Who but the Supreme Personality of Godhead, who lies beyond material perception and is the Lord of self-satisfied sages, can possibly save my consciousness, which has been stolen by a prostitute?
Text 16: Because I allowed my intelligence to become dull and because I failed to control my senses, the great confusion in my mind did not go away, even though Urvaśī herself gave me wise counsel with well-spoken words.
Text 17: How can I blame her for my trouble when I myself am ignorant of my real, spiritual nature? I did not control my senses, and so I am like a person who mistakenly sees a harmless rope as a snake.
Text 18: What is this polluted body anyway — so filthy and full of bad odors? I was attracted by the fragrance and beauty of a woman’s body, but what are those so-called attractive features? They are simply a false covering created by illusion.
Texts 19-20: One can never decide whose property the body actually is. Does it belong to one’s parents, who have given birth to it, to one’s wife, who gives it pleasure, or to one’s employer, who orders the body around? Is it the property of the funeral fire or of the dogs and jackals who may ultimately devour it? Is it the property of the indwelling soul, who partakes in its happiness and distress, or does the body belong to intimate friends who encourage and help it? Although a man never definitely ascertains the proprietor of the body, he becomes most attached to it. The material body is a polluted material form heading toward a lowly destination, yet when a man stares at the face of a woman he thinks, “What a good-looking lady! What a charming nose she’s got, and see her beautiful smile!”
Text 21: What difference is there between ordinary worms and persons who try to enjoy this material body composed of skin, flesh, blood, muscle, fat, marrow, bone, stool, urine and pus?
Text 22: Yet even one who theoretically understands the actual nature of the body should never associate with women or with men attached to women. After all, the contact of the senses with their objects inevitably agitates the mind.
Text 23: Because the mind is not disturbed by that which is neither seen nor heard, the mind of a person who restricts the material senses will automatically be checked in its material activities and become pacified.
Text 24: Therefore one should never let his senses associate freely with women or with men attached to women. Even those who are highly learned cannot trust the six enemies of the mind; what to speak, then, of foolish persons like me.
Text 25: The Supreme Personality of Godhead said: Having thus chanted this song, Mahārāja Purūravā, eminent among the demigods and human beings, gave up the position he had achieved in the planet of Urvaśī. His illusion cleansed away by transcendental knowledge, he understood Me to be the Supreme Soul within his heart and so at last achieved peace.
Text 26: An intelligent person should therefore reject all bad association and instead take up the association of saintly devotees, whose words cut off the excessive attachment of one’s mind.
Text 27: My devotees fix their minds on Me and do not depend upon anything material. They are always peaceful, endowed with equal vision, and free from possessiveness, false ego, duality and greed.
Text 28: O greatly fortunate Uddhava, in the association of such saintly devotees there is constant discussion of Me, and those partaking in this chanting and hearing of My glories are certainly purified of all sins.
Text 29: Whoever hears, chants and respectfully takes to heart these topics about Me becomes faithfully dedicated to Me and thus achieves My devotional service.
Text 30: What more remains to be accomplished for the perfect devotee after achieving devotional service unto Me, the Supreme Absolute Truth, whose qualities are innumerable and who am the embodiment of all ecstatic experience?
Text 31: Just as cold, fear and darkness are eradicated for one who has approached the sacrificial fire, so dullness, fear and ignorance are destroyed for one engaged in serving the devotees of the Lord.
Text 32: The devotees of the Lord, peacefully fixed in absolute knowledge, are the ultimate shelter for those who are repeatedly rising and falling within the fearful ocean of material life. Such devotees are just like a strong boat that comes to rescue persons who are at the point of drowning.
Text 33: Just as food is the life of all creatures, just as I am the ultimate shelter for the distressed, and just as religion is the wealth of those who are passing away from this world, so My devotees are the only refuge of persons fearful of falling into a miserable condition of life.
Text 34: My devotees bestow divine eyes, whereas the sun allows only external sight, and that only when it is risen in the sky. My devotees are one’s real worshipable deities and real family; they are one’s own self, and ultimately they are nondifferent from Me.
Text 35: Thus losing his desire to be on the same planet as Urvaśī, Mahārāja Purūravā began to wander the earth free of all material association and completely satisfied within the self.";
我设法用下面的简化代码重现了这个问题。在我看来这像是一个错误,或者至少是 Aggregate
method. It fails after enumerating a number of around Int32.MaxValue
元素的未记录限制。
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
static void Main(string[] args)
{
var result = GetNumbers().AsParallel().WithDegreeOfParallelism(1)
.Aggregate((long)0, (acc, i) => acc + i, (a, b) => a + b, acc => acc);
Console.WriteLine($"Result: {result:#,0}");
}
static IEnumerable<uint> GetNumbers()
{
for (uint i = 0; i < UInt32.MaxValue; i++)
{
if (i % 10_000_000 == 0 || i > (Int32.MaxValue - 1000))
Console.WriteLine($"Yielding: {i:#,0}");
yield return i;
}
}
}
抛出的异常是:
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey)
at System.Linq.Parallel.AssociativeAggregationOperator`3.AssociativeAggregationOperatorEnumerator`1.MoveNext(TIntermediate& currentElement, Int32& currentKey)
at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
at System.Linq.Parallel.SpoolingTaskBase.Work()
at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
at System.Linq.Parallel.QueryTask.RunTaskSynchronously(Object o)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
异常发生前的确切迭代次数是确定性的,取决于传递给 WithDegreeOfParallelism
.
的值
WithDegreeOfParallelism(1)
: 2,147,483,767
WithDegreeOfParallelism(2)
: 2,147,483,887
WithDegreeOfParallelism(3)
: 2,147,484,007
WithDegreeOfParallelism(4)
: 2,147,484,127
WithDegreeOfParallelism(5)
: 2,147,484,247
.NET Core 3.1.3、.NET Framework 4.8.4150.0、C# 8、Visual Studio 16.5.4
为什么即使我在表达式上应用 unchecked
运算符也会出现溢出异常?
return GetCharStream().AsParallel().Aggregate<char, int[], int[]>(() => new int[26],
(ca, c) =>
{
int i = char.ToUpper(c) - 'A';
if (i > -1 && i < 26)
unchecked { ca[i]++; }
return ca;
},
(ma, la) =>
{
return ma.Zip(la, (t1, t2) => { return unchecked(t1 + t2); }).ToArray();
},
fResult => fResult);
Update:
即使我完全删除代码中的所有算术运算,我仍然得到 arithmetic overflow exception
:-
double[] CountAggregateParallel()
{
//196386
return GetCharStream().AsParallel().Aggregate(() => (new double[26]),
LocalAccumulator,
FinalAccumulator,
fResult => fResult);
}
private static double[] FinalAccumulator(double[] ma, double[] la)
{
return ma;
}
private static double[] LocalAccumulator(double[] ca, char c)
{
return ca;
}
IEnumerable<char> GetCharStream()
{
int i = 0;
while (i < 200_000)
{
foreach (char c in str)
{
yield return c;
}
Console.WriteLine($"{i+1} iteration of str complete");
i++;
}
}
str
变量的值:
string str = @"This chapter explains how unfavorable association is a threat to one’s position in devotional service and how by associating with saintly persons one can attain the highest platform of devotion.
The jīva who has received a human body, which is in itself most conducive toward achieving the Supreme Personality of Godhead, and who has situated himself in the duties of devotional service to the Lord becomes capable of realizing Him, the very identity of spiritual bliss. Such a person, fully dedicated to the Supreme Personality, is liberated from the influence of Māyā; even while continuing to reside in this world created by illusion he is totally untouched by it. Those souls, on the other hand, who are bound up by Māyā are devoted only to their bellies and genitals. They are impure, and by associating with them one will fall down into the dark pit of ignorance.
The emperor Purūravā, who was bewildered by the association of the heavenly lady Urvaśī, later became renounced after being separated from her. He thus sang a song expressing his contempt for womanly connection. He described that persons who are attached to the body of a woman (or a man) — which is simply a mass of skin, meat, blood, sinew, brain tissue, marrow and bones — are not much different from worms. What is the worth of the education, austerity, renunciation, reception of the Vedas, solitary living and silence of one whose mind becomes stolen away by the body of a woman? Learned men should distrust their six mental enemies, headed by lust, and thus avoid associating with women or with men who are controlled by women. After declaring these facts, King Purūravā, now freed from the illusion of material existence, attained realization of the Supreme Lord in His form as the indwelling Supersoul.
In conclusion, one who is intelligent should give up bad association and let himself become attracted to the company of saintly persons. By their transcendental instructions, the saintly devotees of the Lord can break the false attachments of one’s mind. Real saints are always liberated and devoted to the Supreme Personality of Godhead. In their association there are constant discussions about the Supreme Lord, by serving whom the spirit soul completely eradicates his material sins and obtains pure devotional service. And when one gains the devotional service of the Supreme Personality of Godhead, who is the original ocean of unlimited perfect qualities, what else remains to be gained?
Text 1: The Supreme Personality of Godhead said: Having achieved this human form of life, which affords one the opportunity to realize Me, and being situated in My devotional service, one can achieve Me, the reservoir of all pleasure and the Supreme Soul of all existence, residing within the heart of every living being.
Text 2: A person fixed in transcendental knowledge is freed from conditioned life by giving up his false identification with the products of the material modes of nature. Seeing these products as simply illusion, he avoids entanglement with the modes of nature, although constantly among them. Because the modes of nature and their products are simply not real, he does not accept them.
Text 3: One should never associate with materialists, those dedicated to gratifying their genitals and bellies. By following them one falls into the deepest pit of darkness, just like a blind man who follows another blind man.
Text 4: The following song was sung by the famous emperor Purūravā. When deprived of his wife, Urvaśī, he was at first bewildered, but by controlling his lamentation he began to feel detachment.
Text 5: When she was leaving him, even though he was naked he ran after her just like a madman and called out in great distress, “O my wife, O terrible lady! Please stop!”
Text 6: Although for many years Purūravā had enjoyed sex pleasure in the evening hours, still he was not satisfied by such insignificant enjoyment. His mind was so attracted to Urvaśī that he did not notice how the nights were coming and going.
Text 7: King Aila said: Alas, just see the extent of my delusion! This goddess was embracing me and held my neck in her grip. My heart was so polluted by lust that I had no idea how my life was passing.
Text 8: That lady cheated me so much that I did not even see the rising or setting of the sun. Alas, for so many years I passed my days in vain!
Text 9: Alas, although I am supposed to be a mighty emperor, the crown jewel of all kings on this earth, just see how my bewilderment has rendered me a toy animal in the hands of women!
Text 10: Although I was a powerful lord with great opulence, that woman gave me up as if I were no more than an insignificant blade of grass. And still, naked and without shame, I followed her, crying out to her like a madman.
Text 11: Where are my so-called great influence, power and sovereignty? Just like an ass being kicked in the face by his she-ass, I ran after that woman, who had already given me up.
Text 12: What is the use of a big education or the practice of austerities and renunciation, and what is the use of studying religious scriptures, of living in solitude and silence, if, after all that, one’s mind is stolen by a woman?
Text 13: To hell with me! I am such a fool that I didn’t even know what was good for me, although I arrogantly thought I was highly intelligent. Although I achieved the exalted position of a lord, I allowed myself to be conquered by women as if I were a bullock or a jackass.
Text 14: Even after I had served the so-called nectar of the lips of Urvaśī for many years, my lusty desires kept rising again and again within my heart and were never satisfied, just like a fire that can never be extinguished by the oblations of ghee poured into its flames.
Text 15: Who but the Supreme Personality of Godhead, who lies beyond material perception and is the Lord of self-satisfied sages, can possibly save my consciousness, which has been stolen by a prostitute?
Text 16: Because I allowed my intelligence to become dull and because I failed to control my senses, the great confusion in my mind did not go away, even though Urvaśī herself gave me wise counsel with well-spoken words.
Text 17: How can I blame her for my trouble when I myself am ignorant of my real, spiritual nature? I did not control my senses, and so I am like a person who mistakenly sees a harmless rope as a snake.
Text 18: What is this polluted body anyway — so filthy and full of bad odors? I was attracted by the fragrance and beauty of a woman’s body, but what are those so-called attractive features? They are simply a false covering created by illusion.
Texts 19-20: One can never decide whose property the body actually is. Does it belong to one’s parents, who have given birth to it, to one’s wife, who gives it pleasure, or to one’s employer, who orders the body around? Is it the property of the funeral fire or of the dogs and jackals who may ultimately devour it? Is it the property of the indwelling soul, who partakes in its happiness and distress, or does the body belong to intimate friends who encourage and help it? Although a man never definitely ascertains the proprietor of the body, he becomes most attached to it. The material body is a polluted material form heading toward a lowly destination, yet when a man stares at the face of a woman he thinks, “What a good-looking lady! What a charming nose she’s got, and see her beautiful smile!”
Text 21: What difference is there between ordinary worms and persons who try to enjoy this material body composed of skin, flesh, blood, muscle, fat, marrow, bone, stool, urine and pus?
Text 22: Yet even one who theoretically understands the actual nature of the body should never associate with women or with men attached to women. After all, the contact of the senses with their objects inevitably agitates the mind.
Text 23: Because the mind is not disturbed by that which is neither seen nor heard, the mind of a person who restricts the material senses will automatically be checked in its material activities and become pacified.
Text 24: Therefore one should never let his senses associate freely with women or with men attached to women. Even those who are highly learned cannot trust the six enemies of the mind; what to speak, then, of foolish persons like me.
Text 25: The Supreme Personality of Godhead said: Having thus chanted this song, Mahārāja Purūravā, eminent among the demigods and human beings, gave up the position he had achieved in the planet of Urvaśī. His illusion cleansed away by transcendental knowledge, he understood Me to be the Supreme Soul within his heart and so at last achieved peace.
Text 26: An intelligent person should therefore reject all bad association and instead take up the association of saintly devotees, whose words cut off the excessive attachment of one’s mind.
Text 27: My devotees fix their minds on Me and do not depend upon anything material. They are always peaceful, endowed with equal vision, and free from possessiveness, false ego, duality and greed.
Text 28: O greatly fortunate Uddhava, in the association of such saintly devotees there is constant discussion of Me, and those partaking in this chanting and hearing of My glories are certainly purified of all sins.
Text 29: Whoever hears, chants and respectfully takes to heart these topics about Me becomes faithfully dedicated to Me and thus achieves My devotional service.
Text 30: What more remains to be accomplished for the perfect devotee after achieving devotional service unto Me, the Supreme Absolute Truth, whose qualities are innumerable and who am the embodiment of all ecstatic experience?
Text 31: Just as cold, fear and darkness are eradicated for one who has approached the sacrificial fire, so dullness, fear and ignorance are destroyed for one engaged in serving the devotees of the Lord.
Text 32: The devotees of the Lord, peacefully fixed in absolute knowledge, are the ultimate shelter for those who are repeatedly rising and falling within the fearful ocean of material life. Such devotees are just like a strong boat that comes to rescue persons who are at the point of drowning.
Text 33: Just as food is the life of all creatures, just as I am the ultimate shelter for the distressed, and just as religion is the wealth of those who are passing away from this world, so My devotees are the only refuge of persons fearful of falling into a miserable condition of life.
Text 34: My devotees bestow divine eyes, whereas the sun allows only external sight, and that only when it is risen in the sky. My devotees are one’s real worshipable deities and real family; they are one’s own self, and ultimately they are nondifferent from Me.
Text 35: Thus losing his desire to be on the same planet as Urvaśī, Mahārāja Purūravā began to wander the earth free of all material association and completely satisfied within the self.";
我设法用下面的简化代码重现了这个问题。在我看来这像是一个错误,或者至少是 Aggregate
method. It fails after enumerating a number of around Int32.MaxValue
元素的未记录限制。
using System;
using System.Collections.Generic;
using System.Linq;
public static class Program
{
static void Main(string[] args)
{
var result = GetNumbers().AsParallel().WithDegreeOfParallelism(1)
.Aggregate((long)0, (acc, i) => acc + i, (a, b) => a + b, acc => acc);
Console.WriteLine($"Result: {result:#,0}");
}
static IEnumerable<uint> GetNumbers()
{
for (uint i = 0; i < UInt32.MaxValue; i++)
{
if (i % 10_000_000 == 0 || i > (Int32.MaxValue - 1000))
Console.WriteLine($"Yielding: {i:#,0}");
yield return i;
}
}
}
抛出的异常是:
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Linq.Parallel.PartitionedDataSource`1.ContiguousChunkLazyEnumerator.MoveNext(T& currentElement, Int32& currentKey)
at System.Linq.Parallel.AssociativeAggregationOperator`3.AssociativeAggregationOperatorEnumerator`1.MoveNext(TIntermediate& currentElement, Int32& currentKey)
at System.Linq.Parallel.StopAndGoSpoolingTask`2.SpoolingWork()
at System.Linq.Parallel.SpoolingTaskBase.Work()
at System.Linq.Parallel.QueryTask.BaseWork(Object unused)
at System.Linq.Parallel.QueryTask.RunTaskSynchronously(Object o)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
异常发生前的确切迭代次数是确定性的,取决于传递给 WithDegreeOfParallelism
.
WithDegreeOfParallelism(1)
: 2,147,483,767WithDegreeOfParallelism(2)
: 2,147,483,887WithDegreeOfParallelism(3)
: 2,147,484,007WithDegreeOfParallelism(4)
: 2,147,484,127WithDegreeOfParallelism(5)
: 2,147,484,247
.NET Core 3.1.3、.NET Framework 4.8.4150.0、C# 8、Visual Studio 16.5.4